【发布时间】:2023-03-23 10:31:01
【问题描述】:
我遇到了 FindOne 的异步问题。我有一个名为 idChildren 的 id 数组(如 [ [516152], [158796], [123654, 147852] ]),我想检查数组中当前位置的 id 是否在数据库中。 children 是一个数组,我在其中保存包含所有信息的字符串。
for (var j = 0; j < idChildren.length; j++)
{
async.eachSeries(idChildren, function() {
for (var i = 0; i < idChildren[j].length; i++)
{
Children.findOne({ _id: idChildren[j] }, function (err, child) {
console.log("I'm in the findOne");
if (child != undefined && !err) {
if (child.lastname == undefined)
tmp2 += ',';
else
tmp2 += child.lastname + ',';
if (child.firstname == undefined)
tmp2 += ',';
else
tmp2 += child.firstname + ',';
if (child.birthday == undefined)
tmp2 += ',';
else
tmp2 += child.birthday + ',';
tmp2 += '\n';
}
children.push(tmp2);
tmp2 = "";
});
}
});
}
console.log(children);
问题是 "console.log(children)" 打印 [ , , ] 并且在 "I'm in the findOne" 三遍之后。我认为这是我的 async.eachSeries 不正确。 你能帮帮我吗?
编辑
async.eachSeries(idChildren, function(idChild, next) {
Children.findOne({ _id: idChild }, function (err, child) {
console.log("I'm in the findOne");
if (child != undefined && !err) {
if (child.lastname == undefined)
tmp2 += ',';
else
tmp2 += child.lastname + ',';
if (child.firstname == undefined)
tmp2 += ',';
else
tmp2 += child.firstname + ',';
if (child.birthday == undefined)
tmp2 += ',';
else
tmp2 += child.birthday + ',';
tmp2 += '\n';
}
children.push(tmp2);
tmp2 = "";
next();
return;
});
});
console.log(children);
输出是:
[]
我在 findOne
我在 findOne
我在 findOne
我在 findOne
我在 findOne
因此,console.log(children) 会在 FindOne 循环运行之后首先执行。 如果console.log(children)在findOne结尾,则数组是正确的。
【问题讨论】:
-
我编辑了我的答案
标签: javascript node.js mongodb asynchronous mongoose