简体   繁体   中英

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?

Convert each iteration into it's own awaitable and wait for them all to finish eg

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM