Lucas Breitembach
Lucas Breitembach

Reputation: 1683

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});

        });

    }

};

Upvotes: 1

Views: 1718

Answers (3)

sklimkovitch
sklimkovitch

Reputation: 271

const regexForFileName = '.*' + fileName + '.*';
var db = model.getDatastore().manager;
var rawMongoCollection = db.collection(model.tableName);
rawMongoCollection.aggregate(
    [
        {
            $project : {
                "_id" : 0,
                "fileId" : 1,
                "fileName" : 1,
                "fileSize" : 1,
                "createdTime" : 1
            }
        },
        { 
            $match : {
                "fileName" : { 
                    $regex: regexForFileName,
                    $options: 'i'
                }
            }
        },
        {
            $sort: {
                "createdTime" : -1
            }
        },
        {
            $skip: pageNumber * numberOfResultsPerPage
        },
        {
            $limit: numberOfResultsPerPage
        }
    ]
).toArray((err, results) => {
    if (err) {
        console.log(err);
    }
    console.log("results: " + JSON.stringify(results));
});

Upvotes: 0

nopuck4you
nopuck4you

Reputation: 1700

As of Sails v1.0 the .native() method is deprecated in favor of getDatastore().manager.

https://sailsjs.com/documentation/reference/waterline-orm/models/native

Due to a bug with the current version of sails-mongo (v1.0.1) which doesn't support the new required cursor method I've actually switched to using Mongo View's to manage aggregate queries.

The pattern below is "supposed" to work but currently returns no results because toArray() of an aggregate() function is currently not properly supported. It returns an AggregateCursor which does not support the toArray() method.

WHAT I ENDED UP DOING

const myView = sails.getDatastore().manager.collection("view_name");

myView.find({...match/filter criteria...}).toArray((err, results) => {
            if (err) {
              // handle error 2
            }

            // Do something with your results
          });

The entire Aggregate query I put into the Mongo DB View and added additional columns to support filter/match capabilities as needed. The only portion of "match" I did not place into Mongo are the dynamic fields which I use above in the find() method. That's why you need the additional fields since find() will only query the columns available in the query and not the underlying model

WHAT SHOULD HAVE WORKED

So the pattern for aggregate would now be as follows:

const aggregateArray = [
  {
    $project: {
      data: { $substr: ['$pt', 0, 10] },
      prodTempo: { $substr: ['$sis', 0, 10] }
    }
  }
];

sails.getDatastore('name of datastore').manager.collection('collection name')
      .aggregate(aggregateArray)
      .toArray((err, results) => {
        if (err) {
          // handle error 2
        }

        // Do something with your results
      });

Upvotes: 4

Manuel Reil
Manuel Reil

Reputation: 508

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
      });
  }
});

Upvotes: 2

Related Questions