I have two collections: clients and facility. facility.clientId = clients._id I want to join the objects but can't find any good code examples. I've looked at lookup but can't get it to work I want a count of facility with facility.clientId = clients._id So an output if:
[
{
"_id": "1",
"firstname": "Blue",
"address1": "Address 1",
"address2": "Address 2",
"city": "Dublin",
"count": "2",
"__v": 0
},
{
"_id": "2",
"firstname": "Red",
"address1": "Address 1",
"address2": "Address 2",
"city": "Dublin",
"count": "1",
"__v": 0
},
{
"_id": "3",
"firstname": "Green",
"address1": "Address 1",
"address2": "Address 2",
"city": "Dublin",
"count": "0",
"__v": 0
}
]
where count is number of facility.clientId = clients._id
var clientsModel = require('../models/clientsModel.js');
var facilityModel = require('../models/facilityModel.js');
list: function (req, res) {
clientsModel.find({}, null, {sort: '_id'}, function (err, clientss) {
Object.keys(clientss).forEach(function(key) {
facilityModel.count({clientId: clientss[key]._id}, function(err, c) {
console.log('Count is ' + c + " key:" + key);
clientss[key].count = c;
});
});
return res.json(clientss);
});
},
I have tried everything but can't get it to work, please any code examples to point me in the right direction would be nice.
I know there is several examples of lookup and aggregate query but I just don't get it to work.