1

我正在尝试学习用于 MongoDB 和 node.js 的 Mongoose ORM。我想在我的数据库中查询文档,对每个文档执行一个操作,然后在之前的所有操作完成后执行另一个操作。换句话说,我想做这样的事情,假设我有一个名为“用户:”的模型

var userArray = [];
User.find({})
.each(function(user) {
    user.age += 1;
    userArray.push(user);
})
.then(function() {
    //do something with userArray
    //happens after all the users' ages are modified
});

在 Mongoose 中执行此类操作的正确语法是什么?

4

2 回答 2

2

如果您只需要对每个文档执行同步操作,则解决方案相当简单。(console.warn() 是同步的,因此您可以使用它来验证是否首先处理了所有用户对象。)

User.find({}).execFind(function(err, users) {
     users.forEach(function(user) {
          user.age += 1;
          userArray.push(user);
          console.warn('x');
     });
     // then...
     console.warn('y');
});

如果您需要执行某种异步操作(可能是另一个数据库查询),则解决方案会变得更加复杂。我最近遇到了这个问题,并简要讨论了使用 Step 之类的模块或滚动我自己的准系统解决方案。Step 提供了比我需要的更多的功能,所以我认为增加的开销是不值得的。这是我的解决方案:

    var count = 0;
A.find({ b : c }, ['d', 'e', 'f']).sort(['d'], -1).execFind(function(err, g) {
    g.forEach(function(h) {
        h.a = [];
        B.find({ b : c }, ['d', 'e', 'f', 'g']).execFind(function(err, z) {
            g.v = z;
            if (++count == g.length)
                res.render('z.jade', { locals : { title : 'Q', j : g } });
        });
    });
});

请原谅这种混淆(我从一个未公开的项目的源代码中删除了它)。本质上,您要等到最后的异步操作完成。

于 2011-06-24T22:02:32.240 回答
1

有这方面的模块。尝试使用异步(https://github.com/caolan/async)。它允许运行命令,然后在所有完成后执行回调。

async.parallel([
    function(){ ... },
    function(){ ... }
], callback);
于 2012-09-05T20:14:00.760 回答