6

How do I obtain the sum of a Loopback PersistedModel?

There does not seem to be a documentation on how to achieve that.

If possible I would like to avoid having to find all the rows and sum it in Node.js.

UPDATE

Trying out the example from https://github.com/strongloop/loopback/issues/890

var bookCollection = Book.getDataSource().connector.collection(Book.modelName);

I got an error

throw new Error('MongoDB connection is not established');

How do I get a handle on the collection to manually run aggregate query on a MongoDB collection?

Jee Mok
  • 6,157
  • 8
  • 47
  • 80
uzyn
  • 6,625
  • 5
  • 22
  • 41
  • Also saw this https://github.com/strongloop/loopback/issues/890 Anyone has any way to workaround this? Even if it's a non-loopback way. – uzyn Jun 06 '15 at 07:30

2 Answers2

15

Finally managed to get it working. Most examples left out the connect() part.

My working code:

Book.getDataSource().connector.connect(function(err, db) {
  var collection = db.collection('Book');
  var author = Book.getDataSource().ObjectID(authorId);
  collection.aggregate([
    { $match: { authorId: author } },
    { $group: {
      _id: authorId,
     total: { $sum: "$price" }
    }}
  ], function(err, data) {
    if (err) return callback(err);
    return callback(null, data);
  });
});
uzyn
  • 6,625
  • 5
  • 22
  • 41
  • 2
    It doesn't need to connect. My code works fine with the example on https://github.com/strongloop/loopback/issues/890 – achintverma Apr 03 '16 at 16:15
  • Thank you @uzyn! I think there are corner cases where the model may not be connected, and this is needed just in case. – Mike Crowe Sep 15 '16 at 12:34
  • Hey, I got an error like aggregate is not function. Can you please help me out? – Naimish Kher Aug 20 '18 at 06:50
  • what format has the data object in your function? when I try to log it in it is AggregateCoursor and I don't really know how to properly get the data out of it. And I see that you are passing that to the callback directly. does it work? – akkonrad Sep 28 '18 at 11:44
1

Aggregate query with loopback

Products.getDataSource().connector.connect(function(err, db) {
     var collection = db.collection('Products');
        collection.aggregate(
       [{ $match: { "productCode" : "WIN10-NoOS" } }]
        ).toArray(function(err,servicesData){
              if(err){

               }else{
             cb(null,servicesData);
           }

         });
    });
sudheer nunna
  • 1,659
  • 15
  • 17