从聚合迭代Mongodb游标 [英] Iterate over Mongodb cursor from aggregate
问题描述
这是来自我的node.js后端的代码:
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");
});
}
});
我已尝试按照以下建议用toArray()
和each()
替换next()
:
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?
是不是因为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 handles an aggregate to cursor object differently than Mongodb-native as you posted in your link. More information here: mongoose aggregate cursor documentation
这篇关于从聚合迭代Mongodb游标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!