Skip to content Skip to sidebar Skip to footer

Function To Swap Values In Nodejs W/ Mongo+mongoose

Im trying to create a route that takes in 2 dates and swap those dates with each other in the database. the console is printing but the data in the db isn't changing // @route

Solution 1:

From Mongo UpdateOne Documentation UpdateOne takes 3 arguments filter,update,callback, so i believe u need to pass _id of the collection to change.

Update- find() returns a cursor and to use foreach convert it to an array using find().toArray().then(..so on)

// @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.find().toArray().then(cards=>cards.forEach(card => {
    if (card.date === firstDate) {
      return card.updateOne( { date: firstDate } ,{ $set: { date: secondDate } });
    } elseif (card.date === secondDate) {
      return card.updateOne( { date: secondDate },{ $set: { date: firstDate } });
    } else {
      return card;
    }
  });
}))
.then(() =>console.log("working"));
 });

Post a Comment for "Function To Swap Values In Nodejs W/ Mongo+mongoose"