[英]Node.js how to select from MongoDB inside a for or foreach?
I have this code: 我有以下代码:
result.rides.forEach(function(ride) {
var query = {
"by.phone": req.body.myPhone,
"inRide": ride["_id"].toString(),
};
db.offers.findOne(query, function(err, docs) {
if (docs) {
ride.offered = true;
}
});
});
Now, I want to return the result.rides at the end of the forEach
, how to do that? 现在,我想在forEach
的末尾返回result.rides,该怎么做?
Convert each iteration into it's own awaitable
and wait for them all to finish eg 将每个迭代到它自己的awaitable
,等待他们全部完成如
async func() {
const queries = result.rides.map(r =>
new Promise(async (resolve, reject) => {
try {
const query = {
'by.phone': req.body.myPhone,
'inRide': r._id.toString()
};
const docs = await db.offers(query);
if (docs) {
r.offered = true;
}
return resolve();
} catch (e) {
return reject(e);
}
})
);
await Promise.all(queries);
// do something with rides
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.