简体   繁体   中英

How to populate an array of sub `ref`ed documents mongoose?

I'm working on a MEAN stack app with Mongoose version 4.4.0 and having a problem with populating an array of sub-documents. ( couldn't find solutions elsewhere on SO. )

The following illustrates the structure of the models:

Visa model

var visaSchema = new mongoose.Schema({
  from: {type: Schema.Types.ObjectId, ref: 'Country'},
  to: {type: Schema.Types.ObjectId, ref: 'Country'},
  requirements: [
    {type: Schema.Types.ObjectId, ref: 'Requirement'}
  ]
});

exports.model = mongoose.model('Visa', visaSchema);

Requirement model

var requirementSchema = new mongoose.Schema({
   visa: {type: Schema.Types.ObjectId, ref: "Visa"},
   title: String,
   body: String
});

exports.model = mongoose.model('Requirement', requirementSchema);

The above basically structures a one-to-many relationship between a Visa and a Requirement .

Problem

I am not able to populate the requirements field which in fact is an array of Requirement ref objects.

This is how I'm trying to achieve it:

Visa.find()
   //.populate('from', null, {shortName: from})
   //.populate('to', null, {shortName: to})
   .populate('requirements')
   .exec(function(err, result){
      res.json(result);
   });

Whenever I try to populate the requirements field, it returns an empty array on the requirements key.

However without the population, it returns the array of ObjectIds :

[
   {
     "_id":"56b329878848eba00c0f5535",
     "from"{
          "_id":"56b2db1b57f9e71c1bfbadb9",
          "name":"Germany",
          "shortName":"DE",
          "__v":0
     },
     "to":{
          "_id":"56b2db0f57f9e71c1bfbadb8",
          "name":"Afghanistan",
          "shortName":"AFG",
          "__v":0
     },
     "__v":3,
     "requirements":  [
          "56b331d764585e8c12c14dd1", 
          "56b336431ffc49bc19bf1c96",
          "56b33675443f033c14e26d03"
      ]
   }
]

What am I doing wrong?

Any kind of help would be appreciated.

You could try:

Visa.find()
  .populate([
     { path: "from" },
     { path: "to" },
     { path: "requirements" },
   ])
  .exec(function(err, result){
     res.json(result);
});

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