Search code examples
javascriptnode.jsmongodbexpressbackbone.js

How to execute a query with a `has many` association using MongoDB


I have a setup with Node, Express, and using backbone. Everything works fine and I'm able to retrieve records from by MongoDB collections when they are simple as in getting employees by id or all employees. What I'm having trouble understanding is how to get collections from MongoDB that require a more complex query syntax like the following:

db.employees.aggregate(
   [
     { $group : { _id : "$managerName", employees: { $push: "$fullName" } } }
   ]
)

I currently have the following syntax for extracting the data I want to expose as a json object and bind to the elements in my html page.

exports.findById = function(req, res) {
    var id = parseInt(req.params.id);
    db.collection('employees', function(err, collection) {
        collection.findOne({'id': id}, function(err, item) {
            res.jsonp(item);
        });
    });
};

I want to get a list of all Managers and they employees that report to them and then somehow bind this result set to individual divs that would list a Manager as the List heading, and then all the employees that report to them as list items. The result set will essentially consist of parents and childs. I want to do this dynamically using backbonejs.

Would I be doing something like

exports.findRelations = function(req, res) {
    db.collection('employees', function(err, collection) {
        collection.aggregate({ $group : { _id : "$managerName", employees:{$push: "$fullName" } } }, function(err, item) {
            res.jsonp(item);
        });
    });
};

Solution

  • The aggregation pipeline for MongoDB requires that you pass the operations in an Array. This means the correct query would be:

    db.collection('employees').aggregate([
        { $group : { _id : "$managerName", employees:{$push: "$fullName" } }
      ])
      .toArray(function(err, managers){
        if (err){
          throw err;
        }
    
        res.jsonp(managers);
      });
    

    You'll find details for using the aggregation pipeline with the NodeJS MongoDB driver here: https://docs.mongodb.org/getting-started/node/aggregation/