简体   繁体   中英

2 Update methods in one route to swap date NodeJS, Mongoose+mongoDB

Im trying to create a route that takes in 2 dates and swap those dates with each other in the database.

the update method works outside of the forEach but not inside how can I get to work inside of the forEach ?

// @route   PATCH api/swap
// @desc    replace date
// @access  Public

router.put("/swap", (req, res) => {
  const firstDate = req.body.firstDate;
  const secondDate = req.body.secondDate;

  // console.log(firstDate, secondDate);

  // Card.updateOne({ date: firstDate }, { $set: { date: secondDate } });
  Card.find()
    .then(cards => {
      cards.forEach(card => {
        if (card.date === firstDate) {
          return card.updateOne(
            { date: firstDate },
            { $set: { date: secondDate } }
          );
        } else if (card.date === secondDate) {
          return card.updateOne(
            { date: secondDate },
            { $set: { date: firstDate } }
          );
        } else {
          return card;
        }
      });
    })
    .then(() => console.log("working"));
});

For what you are trying to achieve, you need to use a QueryCursor which would allow you to modify the documents one by one.

You can do something like this,

Card.find()
  .cursor()
  .on('data', function(card) { 

      if (card.date === firstDate) {
          card.set("date", secondDate);
      } else if (card.date === secondDate) {
          card.set("date", firstDate);
      }

      card.save(function(err){
      });  
   })
  .on('end', function() { console.log('Done!'); });

You need to make sure the anonymous function within the forEach supports promises, which can be achieved through the async keyword.

Try this:

      cards.forEach(async (card) => {
          return card.updateOne(
...

In addition, findAndModify() might be a better tool for the job so you can avoid iterating through the entire collection of Card objects on every request and offload that to the query parameter to the database call.

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