我试图创建一个接收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"));
});
从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"));
});