从聚合中迭代Mongodb游标
这是来自我的node.js后端的代码:
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"); }); } });
我试着用toArray()
和each()
代替next()
,如下所示:
http://mongodb.github.io/node-mongodb-native/2.0/tutorials/aggregation/
但是,我每次都收到相同的错误:
TypeError: User.aggregate(...).next is not a function
为什么我不能用任何函数遍历返回的文档?
是因为User
不是一个集合吗?
尝试这个:
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处理聚合到游标对象不同于您在链接中发布的Mongodb-native。 更多信息在这里: mongoose聚集游标文档