我试图将产品id列表存储在数据库中的数组中,并检索最新的数组。这是我的服务器端代码
router.post("/scannedproducts",async(request,response)=>{
console.log(request.body)
const Scannedproducts = new scannedproducts({
ids:request.body
})
Scannedproducts.save()
console.log(Scannedproducts)
const getLatestProduct =await scannedproducts.find().sort({ createdAt: -1 }).limit(1) // 10 latest docs
console.log(getLatestProduct)
})
,但它控制台一个空的id数组。请帮助…
代码中的错误是您应该在调用save()
方法时使用await
解决方案应该是:
router.post("/scannedproducts",async(request,response)=>{
const Scannedproducts = new scannedproducts({
ids:req.body
})
await Scannedproducts.save()
console.log(Scannedproducts)
const getLatestProduct =await scannedproducts.find().sort({ createdAt:-1 }).limit(1) // 10 latest docs
console.log(getLatestProduct)
})
它会解决你的问题,但无论如何,你应该在你的问题中提供scannedProducts
模型,并将整个请求体对象分配给属性是一种不好的做法。您应该将ids数组作为用户输入并将其存储在服务器中我建议你这样写代码:
router.post("/scannedproducts",async(request,response)=>{
const Scannedproducts = new scannedproducts({
ids:req.body.ids
})
await Scannedproducts.save()
console.log(Scannedproducts)
const getLatestProduct =await scannedproducts.find().sort({ createdAt:-1 }).limit(1) // 10 latest docs
console.log(getLatestProduct)
})
谢谢