Currently I have three Collection "User" , "UserLocation" & "UserAddress" which are related with each other.
Below are the Schema
UserModel
var userTable = new Schema({
name: String,
email : String
});
module.exports = mongoose.model('user', userTable );
UserLocationModel
var userLocationTable = new Schema({
location : String,
user_id :{
type : ObjectId,
ref : 'user',
}
});
module.exports = mongoose.model('userLocation',userLocationTable);
UserAddressModel
var userAddressTable = new Schema({
userLocationID : {
type : ObjectID,
ref : 'userLocation',
},
address : String
});
module.exports = mongoose.model('userAddress',userAddressTable);
My Code
UserModel.aggregate([
{
"$lookup": {
"from": "userlocations",
"localField": "_id",
"foreignField": "user_id",
"as": "location"
}
},
{
"$unwind" : "$location"
},
{
"$lookup": {
"from": "useraddresses",
"localField": "location._id",
"foreignField": "userLocationID",
"as": "location.address"
}
},
]).exec((err, data) => {
if (err) throw err;
res.send(data);
})
Current Output
[
{
"_id": "5d8b1e6ca4d1ab5e54f1b8ee",
"name": "Shivam",
"email": "ee@gmail.com",
"__v": 0,
"location": {
"_id": "5d8b1e6ca4d1ab5e54f1b8ef",
"location": "Mumbai",
"user_id": "5d8b1e6ca4d1ab5e54f1b8ee",
"__v": 0,
"address": []
}
},
{
"_id": "5d8b3a740b6fee55ac39a61d",
"name": "ameet",
"email": "ddt@gmail.com",
"__v": 0,
"location": {
"_id": "5d8b3a740b6fee55ac39a61e",
"location": "sion",
"user_id": "5d8b3a740b6fee55ac39a61d",
"__v": 0,
"address": []
}
}
]
Here the problem is I am not able to fetch the data from UserAddress Model. I have tried all the possible ways but unable to fetch the data from UserAddress Collection. Can someone help me in this?