在猫鼬中填充嵌入的文档

populate embedded document in Mongoose

本文关键字:文档 填充      更新时间:2023-09-26

给定:

var productSchema = new Schema({
  name: String,
  details : [{ name: String,  description: String }]
})

var listSchema = new Schema({
  name: String,
  products: [{
    product_id: { type: Schema.Types.ObjectId, ref: 'Product' },
    product_vid: { type: Schema.Types.ObjectId, ref: 'Product.details' }
    }]
})

如何查询仅具有相应product_id的列表,其中包含一个与product_vid匹配的详细信息?

List.findById(list_id)
    .populate({
       path: 'products.product_id',
       populate: {
         path: 'products.product_vid'
       }
     })
     .exec(function(err, doc){
       ......
}

不需要

product_vid: {
type: Schema.Types.ObjectId, ref: 'Product.details'}

在列表架构中。

var productSchema = new Schema({
name: String,
details : [{ name: String,  description: String }]
     })

var listSchema = new Schema({
   name: String,
   products: [{ type: Schema.Types.ObjectId, ref: 'Product' }])
      List.findById(list_id)
        .populate({
              path: 'products',
              match: { details: "your matching value"})
           .exec(function(err, doc){
                  ......
      }
这是

错误的

product_vid: { type: Schema.Types.ObjectId, ref: 'Product.details' }

细节是模型的字段,而不是模型本身。

它应该是这样的..

 var listSchema = new Schema({
   name: String,
   products: [{ type: Schema.Types.ObjectId, ref: 'Product' }],
})

然后

 populate('products')

或者可能

 populate('products products.details')

试着让我知道。