【问题标题】:Mongoose Populate - array猫鼬填充 - 数组
【发布时间】:2014-04-19 02:48:25
【问题描述】:

有人可以帮我解决这个架构的人口问题吗?我需要通过他们的 userId 填充员工数组。

var PlaceSchema = new Schema ({
    name:       { type: String, required: true, trim: true },
    permalink:  { type: String },
    country:    { type: String, required: true },
         ...long story :D...
    staff:      [staffSchema],
    admins:     [adminSchema],
    masterPlace:{ type: Boolean },
    images:     []

});

var staffSchema = new Schema ({
    userId: { type: Schema.Types.ObjectId, ref: 'Account' },
    role: { type: Number }
});

var adminSchema = new Schema ({
    userId: { type: Schema.Types.ObjectId, ref: 'Account'}
})

var Places = mongoose.model('Places', PlaceSchema);

我尝试使用此查询,但没有成功。

Places.findOne({'_id' : placeId}).populate('staff.userId').exec(function(err, doc){
    console.log(doc);
});

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-populate


    【解决方案1】:

    Polpulation 旨在作为一种从集合中的相关模型中“提取”信息的方法。因此,与其“直接”指定相关字段,不如引用相关字段,以便文档似乎嵌入所有这些子文档在回复中:

    Places.findOne({'_id' : placeId}).populate('staff','_id')
        .exec(function(err, doc){
        console.log(doc);
    });
    

    第二个参数只返回你想要的字段。所以它“过滤”了响应。

    文档中有关于populate 的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-13
      • 2020-01-30
      • 2016-04-28
      • 2014-11-25
      • 2019-07-17
      • 2015-07-13
      • 2016-10-10
      相关资源
      最近更新 更多