Node.js mongoose和async

时间:2015-07-31 22:35:49

标签: node.js asynchronous mongoose

js mongoose和async。我需要帮助来确定任务是否完整,以便我可以渲染一个html页面。 mongoose查询和异步完成任务。我已根据需要测试了代码和数据库的正确更新。但是,我不确定在哪里呈现页面,因为我不知道代码何时完成任务。我希望有人能给我一个答案!谢谢

router.get('/initialize', function (req, res, next) {
    if (req.session.passport.user.accountType == "Admin" ||
        req.session.passport.user.accountType == "Manager") {
        var date = new Date();
        var requestDate = null;
        if (date.getMonth() + 1 < 10) {
            requestDate = new Date(date.getFullYear() + '-0' + (date.getMonth() + 1) + '-' + date.getDate());
        } else {
            requestDate = new Date(date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate());
        }

        var i = 0;
        Relationship.find({manager : { $ne: null }}, function (err, manageRelationshipObject) {
            async.each(manageRelationshipObject, function (relationshipData, callback) {
                Relationship.find({username : relationshipData.username, customerID : { $ne: null }}, function (err, customRelationshipObject) {
                    async.each(customRelationshipObject, function (data, callback) {
                        var managerObject = relationshipData.manager;
                        var workerObject = data.username;
                        var customerObject = data.customerID;
                        i++;
                        Entry.findOneAndUpdate({
                            recordDate: requestDate,
                            customerID: customerObject,
                            workerID: workerObject,
                            managerID: managerObject
                        }, {
                            recordDate: requestDate,
                            customerID: customerObject,
                            workerID: workerObject,
                            managerID: managerObject
                        }, {upsert: true}, function (err, object) {
                            if (err) {
                                return res.send(err);
                            }

                        });


                    });

                });
            });
        });

    }
});

1 个答案:

答案 0 :(得分:0)

async.each需要3个参数。

  • 第一个是数组(manageRelationshipObject)√
  • 第二个是要在该数组上应用的迭代器函数(Relationship.find)√
  • 第三个是最终回调功能,一切都完成后。 ()x

看起来你只需要添加第3个参数就可以了。

下面是更详细的文档:https://github.com/caolan/async