mongoose中嵌套查询执行的问题

Issue with Nested query execution in mongoose

本文关键字:问题 执行 查询 嵌套 mongoose      更新时间:2023-09-26

我正在尝试以下查询。我写这篇文章是为了获得文档列表,对于每个文档,我需要运行一些逻辑来获得标记列表。使用这个标签列表,我用获得的标签列表更新文档。

我得到的"updateAndPrint"函数的标记列表为空。我想这是一个承诺即将出现的问题。

以下是查询:

DB.todoTable.find()
    .limit(10)
    .exec(function (err, todos) {
        var tags = [];
        for (var todo in todos) {
            var text = todos[todo].text;
            var id = todos[todo]._id;
            console.log(text);
            tags = getTagsList(text);
            (function updateAndPrint(id, tags) {
                DB.todoTable.update({_id: id}, {$addToSet: {tags: {$each: tags}}},
                    function (err, numberUpdated, result) {
                        if (err) throw err;
                        (function printResult(id) {
                            DB.todoTable.findOne({_id: id})
                                .exec(function (err, todo) {
                                    if (err) throw err;
                                    console.dir(todo.tags);
                                });
                        })(id);
                    });
            })(id, tags);
        }
        console.dir(tags);
    });

如何运行此查询。或者有没有更好的方法来实现同样的逻辑。

编辑

在运行更新操作之前,必须执行'tags=getTagsList(text)'。

使用findAndModify而不是更新并设置选项{new: true}

更新

您可以将要作为回调调用的函数传递给findTags,因此findTags(text)将具有findTags(text, callback),其中回调将为updateAndPrint函数。因此,当您在findTags中获得所有数据时,您可以调用callback