填充mongoose中的子文档

时间:2015-02-10 09:23:09

标签: node.js mongodb mongoose

我有这个文件:

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

它是一个类别架构,其中typeComponents包含一个包含该类别产品的列表。

我的模特:

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

是否可以填充typeComponents?

我试过了:

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)
      });

    });

1 个答案:

答案 0 :(得分:1)

您缺少填充路径的.typeComponents部分。

当我在typecomponents集合中使用您的文档和几个文档尝试使用匹配的_id值时,这是有效的:

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)
  });
});