带有Mongo + Mongoose的NodeJS中的值交换函数 [英] Function to swap values in NodeJS w/ mongo+mongoose

查看:78
本文介绍了带有Mongo + Mongoose的NodeJS中的值交换函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个包含2个日期的路由,并将这些日期在数据库中彼此交换.

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   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"));
});

推荐答案

来自

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

Updatefind()返回一个游标,并使用foreach将其转换为使用find().toArray().then(..so on)

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

这篇关于带有Mongo + Mongoose的NodeJS中的值交换函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆