简体   繁体   中英

Populate subdocuments in mongoose

I have this document:

[
  {
     _id: "54d278b2b6d57eee9f2c6d02",
     title: "Piping",
     mainCategories: [
       {
         title: "Shut valves",
         subCategories: [
           {
             title: "Ball valve",
             userCodeSyntax: "AV2",
             typeComponents: [
               "54d278b2b6d57eee9f2c6d00",
               "54d278b2b6d57eee9f2c6d01"
             ]
           }
         ]
       }
     ]
   }
]

It's a category schema where typeComponents contains a list with products in that category.

My model:

var disciplineSchema = new Schema({
  title: {type:String, required:true},
  project:{
    type: Schema.ObjectId,
    ref: 'Project'
  },
  mainCategories:[
    {
      title: {type:String, required: true},
      subCategories:[
        {
          title: {type:String, required: true},
          userCodeSyntax: {type:String, required: true},
          externalCode:String,
          typeComponents:[ {type: Schema.ObjectId, ref: 'TypeComponent'}]
        }
      ]
    }
  ]
});

Is it possible to populate typeComponents?

I tried this:

mongoose.model('Discipline').find()
    .exec(function(err, disciplines){
      var options = {
        path: 'mainCategories.subCategories',
        model: 'TypeComponent'
      };

      mongoose.model('Discipline').populate(disciplines, options, function (err, res) {
        callback.status(200).send(res)
      });

    });

You are missing the .typeComponents part of the path to populate.

This worked when I tried it with your doc and a couple of docs in the typecomponents collection with matching _id values:

mongoose.model('Discipline').find()
.exec(function(err, disciplines){
  var options = {
    path: 'mainCategories.subCategories.typeComponents',
    model: 'TypeComponent'
  };

  mongoose.model('Discipline').populate(disciplines, options, function (err, res) {
    callback.status(200).send(res)
  });
});

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