简体   繁体   中英

node.js - populate embedded document in Mongoose

Given:

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' }
    }]
})

How can I do the query for the List with only corresponding product_id with one details matching product_vid in it?

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

There is no need for

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

in listSchema.

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){
                  ......
      }

This is wrong

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

detail is field of a model. and not model itself.

it should be something like..

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

and then

 populate('products')

or probably

 populate('products products.details')

Just try and let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM