【问题标题】:mongoose populate doesn't work with array of IDs猫鼬填充不适用于 ID 数组
【发布时间】:2021-11-08 02:33:32
【问题描述】:

我有这 3 个模型 User、Product 和 Orders,并且相互之间也有引用。

我的订单架构:

const orderSchema = Schema({

buyerId:{
    type: Schema.Types.ObjectId,
    ref: 'User'
},
totalAmount: {
    type: Number,
    required: [true, "description is required"]
},
    createdOn: {
    type: Date,
    default: new Date()
},
    items:[{type:Schema.Types.ObjectId, ref: 'Product'}]})

我正在尝试像这样使用 populate():

    Order.find()
    .populate('buyerId')//Reference to User Model
    .populate('items')// Reference to Product Model
    .exec(function (err, result){

        console.log(result);// RETURNS ONLY buyerId populated
        console.log(result.buyerId.name);//Successfully references to my User model and prints name
        console.log(result.items);//Prints Undefined

    })

您可以在上面看到我的控制台日志,它返回的只是填充的buyerId(仅从我的用户模型中获得参考)

似乎我的 populate('items') 根本不起作用。 items 字段包含 ID 数组,其中 ID 是产品的 ID。我需要同时参考用户和产品。我只是在关注猫鼬中的文档,我不知道我可能做错了什么。

【问题讨论】:

  • 我认为查找更好,如果你想我创建查询
  • 是的,你能帮我吗
  • 如果不放 .populate('items'),items 是否包含 id 列表或仍然未定义?因为,那么您在订单中添加新产品的方式或模型可能存在问题。
  • @jeremynac 如果我删除它并留下填充买家 ID,我可以参考并从用户集合中获取数据
  • 好的,如果你只输入.populate('items'),项目是否已填充?

标签: javascript node.js mongodb mongoose


【解决方案1】:

使用聚合

Order.aggregate([
    { $match:{ user:"sample_id"
     }
    },
    {$lookup:{
        from:'users', // users collection name
        localField:'buyerId',
        foreignField:'_id',
        as:'buyerId'
    }},
    {
        $lookup:{
            from:'items', //items collection name
            localField:'items',
            foreignField:'_id',
            as:'items'
        }
    },

])

【讨论】:

  • 我如何将它们引用为:字段和:buyerId?如何输出结果?我在代码末尾连接了 .then(result) 并在控制台记录了它,但只是从 Order 集合中获取了文档
  • lookup as field 将填充的数据作为我们在查找中定义为as 的值的字段名称,from 是您要填充的每个模式的集合名称,我不知道集合名称,所以我只需进行查询以将其更改为您的环境
  • 哦,我想我现在明白了。谢谢,我会在这里更新。
  • 谢谢问题已解决。我已经处理了好几个小时了。
  • 你现在可以添加另一个阶段比赛我会更新我的答案
猜你喜欢
  • 2015-07-13
  • 2021-03-12
  • 2014-04-19
  • 1970-01-01
  • 2015-07-13
  • 2016-10-10
  • 2020-01-30
  • 2020-01-17
相关资源
最近更新 更多