문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top