【发布时间】:2022-02-12 22:30:28
【问题描述】:
我正在尝试使用 react、node 和 mongodb 创建一个电子商务网站。 我创建了包含 cmdRef(字符串)、theClient(用户的 ID)和产品数组(带有 ProductId 和 qty)的订单模式,如下面的代码:
Orderchema=new mongoose.Schema({
CmdRef:String,
Client:{type: mongoose.Schema.Types.ObjectId,
ref: 'User'},
TotalProducts:[{ProductId:{type: mongoose.Schema.Types.ObjectId,
ref: 'Product'},Quantity:Number}],
现在我正在尝试创建获取所有订单的路线
CommandRouter.get('/AllCommands',async(req,res)=>{
try {
const cmd= await Command.find({}).populate({path: 'Client', select: 'firstName lastName'}).populate({path:'TotalProducts'})
//
res.json(cmd)
} catch(error)
{
return res.status(500).send({message : "error get orders"})
}
})
这里我在填充表格中的产品 ID 时发现了一个问题 它填充客户端 ID 并返回有关用户的所有信息,但产品表失败 this is the full response using PostMan
你们对如何在 TotalProducts 表中填充 productId 有任何想法吗?
【问题讨论】:
-
TotalProducts不是参考,ProductId是。 -
thnx @Joe,我知道 ref 是“ProductId”,但它在数组“TotalProducts”中,所以我不知道如何在对象表中填充元素
标签: javascript node.js reactjs mongodb mongoose