Question

I'm using sails with sails-mongo and I'm looking to perform an aggregation across a collection. I want to reuse the connection object that waterline uses, rather than create an entirely new connection to the mongodb server. Is this connection object available somewhere, and can it perform any query type?

This is predicated on the understanding that waterline/sails cannot currently do aggregations.

Était-ce utile?

La solution

It sounds like you're looking for the .native method, which returns the raw node mongo collection instance. This allows you to use native Mongo methods. For example, if you a User model in Sails, you would do:

User.native(function(err, userCollection) {

    userCollection.aggregate(...)

}

Docs for the native Node Mongo driver are here, including a section on how to do aggregation.

Docs for the .native method are on the sailsjs.org.

Autres conseils

Just for less searching and to share experience, here is a working template for mongodb aggregation in Sails.js (for model User) :

User.native(function(err, collection) {
    if (err) return res.serverError(err);

    collection.aggregate(
      [
        //Your matching and grouping here
        //{ $match : { country : user.country } },
        //{ $group: { _id: "$age", count: { $sum: 1 } } }
      ], function(err, result){
           if (err) return res.serverError(err);
           console.log(result);
         }
    );
});

More about aggreagation: http://docs.mongodb.org/manual/tutorial/aggregation-with-user-preference-data/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top