[英]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. 我正在尝试创建一个包含2个日期的路由,并将这些日期在数据库中彼此交换。
the update method works outside of the forEach but not inside how can I get to work inside of the forEach ? update方法在forEach外部起作用,但在内部却不起作用,我如何才能在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. 对于要实现的目标,您需要使用QueryCursor ,它可以让您一个接一个地修改文档。
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. 您需要确保forEach
的匿名函数支持诺言,这可以通过async
关键字实现。
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. 此外, findAndModify()
可能是完成此工作的更好工具,因此您可以避免在每次请求时都遍历Card
对象的整个集合,并将其卸载到数据库调用的query
参数中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.