在NodeJS中交换值的函数w / mongo + mongoose

问题描述 投票:1回答:1

我试图创建一个接收2个日期的路线,并在数据库中互相交换这些日期。

控制台正在打印,但数据库中的数据没有变化

// @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"));
});
javascript arrays node.js mongodb mongoose
1个回答
0
投票

Mongo UpdateOne Documentation UpdateOne需要3个参数过滤,更新,回调,所以我相信你需要传递集合的_id来改变。

Update- find()返回一个游标并使用foreach将其转换为使用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"));
 });
© www.soinside.com 2019 - 2024. All rights reserved.