【发布时间】:2021-05-28 08:09:45
【问题描述】:
我在 MongoDb 中有 2 个集合:users 和 images
用户就像:
{
"_id": ObjectID("58299fc14705d47ff852f8ae"),
"mail": "Qwerty1@test.test",
"username": "Qwerty1",
"token": "g8m7h0phrvhp774cw0xh9qkt9rhu062r2b3gigm0t1o22zkt9",
...,
"images": [
ObjectID("582c547bb7c5cc391e5a1793"),
ObjectID("582c54ecb7c5cc391e5a1794")
]
}
图片就像:
{
"_id": ObjectID("582c5394b522cb37d701dbe3"),
"user": "g8m7h0phrvhp774cw0xh9qkt9rhu06
"image": base64 encoded
}
我在 users 中进行查找以获取该用户图像的 ID,并且我想填充一个数组 ( b64Images ) 对 images 集合的查找请求。
db.collection("users").find({$or : [{ username: req.params.username }, {token : req.params.username}]}).toArray(function (err, result) {
if(result.length){
var b64Images = [];
async.each(result[0].images,
function(item, callback){
db.collection("images").find({_id : item}).toArray(function (err, resulta) {
console.log(resulta[0].user);
b64Images.push(resulta[0].user);
});
callback();
},
function(err){
console.log("finished");
res.json({images : b64Images});
}
}
}
但我的问题是我的循环在 images 的响应中找到之前完成。
所以我有一个空数组。
我知道这是一个异步问题,但我想不通。
【问题讨论】:
标签: javascript node.js mongodb asynchronous