我正在努力理解Mongoose中的填充方法,同时在将字段从一个Mongoose模型填充到另一个模型时遇到困难。第一个模型架构是:
var MprnSchema = new mongoose.Schema({
mprNo: {type: Number, unique: true, required: true},
siteName: String,
buildingNo: Number,
streetAddress: String,
secondAddress: String,
townCity: String,
postCode: String,
supplier: String,
siteContactName: String,
siteContactNo: String,
});
module.exports = mongoose.model("Mprn", MprnSchema);
另一种模式是:
var FaultSchema = new mongoose.Schema({
jobRef: Number,
mprNo: Number,
requestedDate: {type: Date, default: Date.now},
attendedDate: {type: Date, default: null},
siteDetails: {type: mongoose.Schema.Types.ObjectId, ref: 'Mprn'},
faultIssue: String,
});
但是,当我试图用mprn的内容填充“sitedetails”时,当使用下面的代码时,我得到了[]:
Fault.find(reportQuery).populate('siteDetails', 'siteName
postCode').exec((err, faultResults) => {
if(err){
req.flash("error", err.message);
res.redirect("/");
}
console.log(faultResults);
res.render("reportResults", { queryResults: faultResults });
});
传递到要呈现的对象(queryresults)只包含错误数据,而不包含应填充的“sitedetails”。我认为问题可能是当我首先使用fault.create()方法时,我是否应该在此时保存对MPRN模型的引用,以便在填充时有一个要引用的ID?
我的样本集合是:
故障
{
"jobRef": 60000,
"mprNo": 123456,
"faultIssue": "Test"
}
MPRN
{
"mprNo": 123456,
"siteName": "Smithson Gates",
"buildingNo": 76,
"streetAddress": "Garden Place",
"secondAddress": "Greater Manchester",
"townCity": "Salford",
"postCode": "M5 3AP",
"supplier": "test",
"siteContactName": "Mr B Jones",
"siteContactNo": "0161 000 0000"
}
最佳答案
你正在使用最新版本的MongoDB…所以,你可以尝试下面的$lookup
聚合…使用它的好处是您不需要将_id
集合的Mprn
存储在Fault
中。您可以使用mprn
数字轻松加入这两个集合
Fault.aggregate([
{ "$match": reportQuery },
{ "$lookup": {
"from": Mprn.collection.name,
"let": { "mprNo": "$mprNo" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$mprNo", "$$mprNo" ] } } }
],
"as": "siteDetails"
}},
{ "$unwind": "$siteDetails" }
])
关于node.js - 在Node/Express应用程序中使用Mongoose/MongoDB从一个模型填充到另一个模型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51580808/