node.js - node.js - 如何在forEach循环中运行mongoose查询

70 3

谁可以帮助我如何在nodejs中的forEach循环中运行mongoose查询,并且需要联接两个集合的内部结果

如下详细信息


userSchema.find({}, function(err, users) {


 if (err) throw err;


 users.forEach(function(u,i){


 var users = [];


 jobSchema.find({u_sno:s.u.sno}, function(err, j) {


 if (err) throw err;


 if (!u) {


 res.end(JSON.stringify({


 status: \'failed:Auction not found.\',


 error_code: \'404\'


 }));


 console.log("User not found.");


 return 


 }


 users.push(j);


 })


 })


 res.send(JSON.stringify({status:"success",message:"successfully done",data:{jobs:j,users:u}}));


})



时间: 原作者:

112 2

你可以使用:


db.collection.find(query).forEach(function(err, doc) {


 // ...


});



原作者:
98 0

一个不错的解决方案是使用cursor.eachAsync()函数,Credit to https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js 。


 // A cursor has a `.next()` function that returns a promise. The promise


 // will resolve to the next doc if there is one, or null if they are no


 // more results.


 const cursor = MyModel.find().sort({name: 1 }).cursor();



 let count = 0;


 console.log(new Date());


 await cursor.eachAsync(async function(doc) {


 // Wait 1 second before printing first doc, and 0.5 before printing 2nd


 await new Promise(resolve => setTimeout(() => resolve(), 1000 - 500 * (count++)));


 console.log(new Date(), doc);


 });



原作者:
...