我正在尝试以下查询。我写这篇文章是为了获取文档列表,对于每个文档,我需要运行一些逻辑来获取标签列表。使用此标签列表,我使用获得的标签列表更新文档。
我得到的“updateAndPrint”函数的标签列表为空。我想这是一个 promise 出现的问题。
这是查询:
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, callback),而不是
,其中您的回调将是 findTags(text)
updateAndPrint
函数。因此,当您在 findTags
中获取所有数据时,您可以调用回调
。
关于javascript - Mongoose 中嵌套查询执行的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28438527/