【问题标题】:Iterate over Mongodb cursor from aggregate从聚合中迭代 Mongodb 游标
【发布时间】:2016-07-26 07:19:19
【问题描述】:

这是来自我的 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");
        });
    }
});

我已尝试按照此处的建议将 next() 替换为 toArray()each()

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

但是,我每次都收到相同的错误:

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

为什么我不能用任何函数迭代返回的文档?

是不是因为User 不是一个集合?

【问题讨论】:

  • 一种可能的解决方案是简单地传递回调并迭代结果
  • 变量“用户”分配给什么?在提供的链接中,他们连接到数据库,然后将变量设置为该数据库中的集合,您是否也在这样做?
  • @devonJS 用户是一个模型,但我使用的是猫鼬,据我了解,猫鼬会自动将一个集合与每个模型类型关联起来。

标签: node.js mongodb


【解决方案1】:

试试这个:

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 aggregate cursor documentation

【讨论】:

  • 你是一个绝对的传奇。非常感谢
猜你喜欢
  • 2019-05-28
  • 2013-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多