node.jsmongodbsails.jssails-mongo

mongoDB and sails aggregate dont work with nodejs


I'm using mongodb and sails framework, Production.find({}) is working normally but Production.aggregate([]) is returning an error

Production.aggregate() is not a function

module.exports = {

    list : function(req,res) {

        Production.aggregate([{
            $project: {
                data: { $substr: ["$pt",0,10] },
                prodTempo: { $substr: ["$sis",0,10]}
            }


        }])
        .exec(function(err,collection ){
            if(err){
                res.send(500,{error:"DataBase Error"});
            }

            res.view('list',{producao:collection});

        });

    }

};

Solution

  • For aggregations you need to call the native function first. Then it looks like this:

    const aggregateArray = [
      {
        $project: {
          data: { $substr: ['$pt', 0, 10] },
          prodTempo: { $substr: ['$sis', 0, 10] }
        }
      }
    ];
    
    Production.native(function(err, prodCollection) {
      if (err) {
        // handle error 1
      } else {
        prodCollection
          .aggregate(aggregateArray)
          .toArray((err, results) => {
            if (err) {
              // handle error 2
            }
    
            // Do something with your results
          });
      }
    });