【问题标题】:Problem while populating orders and an array of products填充订单和一系列产品时出现问题
【发布时间】: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


【解决方案1】:

产品总数不是ObjectId。您应该改为填充 ProductId

这应该可行。

const cmd = await Command
    .find({})
    .populate([
      {
        path: 'Client', 
        select: 'firstName lastName'
      },
      {
        path: 'TotalProducts'
        populate: 'ProductId'
      }
    ]);

【讨论】:

  • 感谢@Sachin Yadav 抽出宝贵时间,但它仍然无法正常工作,我仍然收到您所说的订单错误,我应该填写产品 ID 表,但我不明白如何
  • @asmasahraoui 抱歉,我之前没有在我的代码中看到错误。我现在已经更新了答案。对于嵌套人口,您需要同时指定 pathpopulate 属性。如果它为您提供正确的结果,请更新我。
  • 非常感谢,这解决了我的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-26
  • 2013-09-29
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 2013-12-01
相关资源
最近更新 更多