簡單填充
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"
}
}