MongoDB aggregation on Loopback

前端 未结 2 1777
臣服心动
臣服心动 2020-12-16 06:04

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 ha

相关标签:
2条回答
  • 2020-12-16 06:48

    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);
               }
    
             });
        });
    
    0 讨论(0)
  • 2020-12-16 07:02

    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);
      });
    });
    
    0 讨论(0)
提交回复
热议问题