【问题标题】:Mongoose: nested ref models populationMongoose:嵌套的参考模型种群
【发布时间】:2014-01-15 23:57:46
【问题描述】:

如何填充嵌套的引用模型?

例如:

// 'Collection' model
var CollectionSchema = new Schema({
  collection_name: String,
  _groups: [{ type: Schema.Types.ObjectId, ref: 'Group' }],
});

// 'Group' model
var GroupSchema = new Schema({
  group_name: String,
  _item: { type: Schema.Types.ObjectId, ref: 'Item' }  // To be populated
  _meta: [ { type: Schema.Types.ObjectId, ref: 'Meta' } // To be populated
});

// 'Item' model
var ItemSchema = new Schema({
  item_name: String,
  item_description: String
});

// 'Meta' model
var MetaSchema = new Schema({
  meta_name: String,
  meta_value: String
});

我想在“集合”模型中填充“_group”中的每个“_item”。 我的意思是得到这样的东西:

{
 collection_name: "I'm a collection"
 _groups: [ 
           { _id: ObjectId("520eabd1da5ff8283c000009"),
              group_name: 'Group1',
              _item: { _id: ObjectId("520eabd1da5ff8283c000004"),
                        item_name: "Item1 name",
                        item_description: "Item1 description"
                    },
             _meta: {
                       _id: ObjectId("520eabd1da5ff8283c000001"),
                      meta_name= "Metadata name",
                      meta_value = "metadata value"
                    }
            },
            { _id: ObjectId("520eabd1da5ff8283c000003"),
              group_name: 'Group2',
              _item: { _id: ObjectId("520eabd1da5ff8283c000002"),
                        item_name: "Item2 name",
                        item_description: "Item2 description"
                    },
             _meta: {
                       _id: ObjectId("520eabd1da5ff8283c000001"),
                      meta_name= "Metadata name",
                      meta_value = "metadata value"
                    }
            }
          ]
}

【问题讨论】:

    标签: node.js data-structures mongoose


    【解决方案1】:

    我宁愿做

    var Group = mongoose.model('Group', GroupSchema);
    
    Group.find().populate('_item _meta').exec(function (error, groups) {
      // ...
    });
    

    【讨论】:

      【解决方案2】:
      var Group = mongoose.model('Group', GroupSchema);
      Group.find().populate('_item').populate('_meta').exec(function (error, groups) {
        //groups will be an array of group instances and
        // _item and _meta will be populated
      });
      

      【讨论】:

        猜你喜欢
        • 2016-07-02
        • 1970-01-01
        • 2017-07-06
        • 2013-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-26
        • 1970-01-01
        相关资源
        最近更新 更多