0

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.

Pkinan
  • 11
  • 1
  • No code here at all attempting a `$lookup`. You're last question was closed for the same reason. Several examples on the linked duplicate, and many more easily accessible with a simple search. And of course the official documentation. If you write something, then we can "correct" you. – Neil Lunn May 02 '18 at 11:53
  • [`$lookup`](https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/) – Neil Lunn May 02 '18 at 20:40

0 Answers0