db2791 db2791 - 4 months ago 37
Node.js Question

Iterate over Mongodb cursor from aggregate

Here is code from my node.js backend:

app.get('/getpossibleconnections', auth, function(req, res){
if (req.authenticated == false){
res.send("Your session has expired.");
} else {
User.aggregate([
{ $match: { _id: { $nin: req.decoded.username.connections } } },
{ $sample: { size: 10 } },
]).next(function(err, docs) {
console.log("horray");
});
}
});


I've tried replacing
next()
with
toArray()
and
each()
as suggested here:

http://mongodb.github.io/node-mongodb-native/2.0/tutorials/aggregation/

However, I receive the same error every time:

TypeError: User.aggregate(...).next is not a function


Why can't I iterate over the returned documents with any sort of function?

Is it because
User
isn't a collection?

Answer

Try this:

var cursor = User.aggregate([
    { $match: { _id: { $nin: req.decoded.username.connections } } },
    { $sample: { size: 10 } },
]).cursor().exec();

cursor.each(function(err, doc) {
    //do something with doc
});

Mongoose handles an aggregate to cursor object differently than Mongodb-native as you posted in your link. More information here: mongoose aggregate cursor documentation

Comments