简单填充

Mongoose populate 用于显示来自其他集合的引用文档的数据。

假设我们有一个 Person 模型,它引用了名为 Address 的文档。

人模型

var Person = mongoose.model('Person', {
    fname: String,
    mname: String,
    lname: String,
    address: {type: Schema.Types.ObjectId, ref: 'Address'}
});

地址模型

var Address = mongoose.model('Address', {
    houseNum: String,
    street: String,
    city: String,
    state: String,
    country: String
});

要使用它的 ObjectId 在 Person 中填充 Address,使用 let 说的 findOne(),使用 populate() 函数并添加字段键 address 作为第一个参数。

Person.findOne({_id: req.params.id})
    .populate('address') // <- use the populate() function
    .exec(function(err, person) {
        // do something.
        // variable `person` contains the final populated data
    });

要么

Person.findOne({_id: req.params.id}, function(err, person) {
    // do something
    // variable `person` contains the final populated data
})
.populate('address');

上面的查询应该生成下面的文档。

人员文件

{
    "_id":"123abc",
    "fname":"John",
    "mname":"Kennedy",
    "lname":"Doe",
    "address":"456def" // <- Address' Id
}

地址文件

{
    "_id":"456def",
    "houseNum":"2",
    "street":"Street 2",
    "city":"City of the dead",
    "state":"AB",
    "country:"PH"
}

填充文件

 {
    "_id":"123abc",
    "fname":"John",
    "mname":"Kennedy",
    "lname":"Doe",
    "address":{
        "_id":"456def",
        "houseNum":"2",
        "street":"Street 2",
        "city":"City of the dead",
        "state":"AB",
        "country:"PH"
    }
}