Populate from One Model to Another Using Mongoose/MongoDB in Node/Express Application

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Populate from One Model to Another Using Mongoose/MongoDB in Node/Express Application



I am struggling to understand the populate method in Mongoose, while having trouble populating fields from one Mongoose model to another. The first model Schema is:


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);



And another Schema is:


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,
});



However, when I try to populate the 'siteDetails' with the contents of Mprn, I get when using thhe code below:


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 });

});



The object passed to be rendered (queryResults) only contains the Fault data and NOT the 'siteDetails' that should be populated. I think the problem may be when I am using the Fault.Create() method in the first place, should I be saving a reference to the MPRN model at this point, so that the there is an Id to be referenced when populating?



My samples collections are:



Fault


{
"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"
}





can you post your sample collection?
– Anthony Winzlet
1 hour ago





I have added the collection data that I am testing this with. These Schemas are actually larger and I have truncated them to a minimum and have added the test data that is applicable.
– ASTIN77
31 mins ago





which is the common (matching key) in both the collections? and what is your mongodb version?
– Anthony Winzlet
26 mins ago





Apologies, the key is mprNo that is matching in each collections ( i have updated the mprNo value) and the MongoDB version is V4.0.0
– ASTIN77
23 mins ago






1 Answer
1



Well you are using latest version of mongodb... So, You can try below $lookup aggregation... and the plus point of using this is you don't need to store _id of Mprn collection in the Fault... You can easily join both the collections with mprn number


$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" }
])





Thanks, but I am not sure how I would use this within an express/Node route?
– ASTIN77
14 mins ago





this is an aggregate query just like a find query of mongodb and also the alternate of populate query... just replace this with your find().populate() query it will work as same and give your desired result... you will learn a lot of things about mongodb after using this query...
– Anthony Winzlet
11 mins ago





Thanks for all your help, but now I am getting db is not defined, should i be replacing db with something else? I am having severe brain-freeze today...
– ASTIN77
4 mins ago







It should be Fault... And Mprn.collection.name is the name of your Mprn collection... you need to import it just you have imported Fault
– Anthony Winzlet
1 min ago


Fault


Mprn.collection.name


Mprn


Fault






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

aHdW0qxDo1BJv6mfdcjY
z5WV4VdYL95 Ok2Sr l GDQ

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

Visual Studio Code: How to configure includePath for better IntelliSense results