使用mongoDB切换布尔值 [英] Toggle a boolean value with mongoDB
问题描述
我正在使用mongoDB数据库,并且想要切换Day对象内的boolean present属性.这是我的工作代码:
I'm working with a mongoDB database and I want to toggle the boolean present attribute inside the Day object. Here is my working code:
exports.modifyPresence = (req, res) => {
action.getStudentCurrentDay(req.body.hash)
.then(
dayId => {
return Day.findOne({_id: dayId});
}
)
.then(
day => {
return Day.findOneAndUpdate({_id: day.id},{$set:{present:!day.present}});
}
)
.then(
() => res.status(200).json("This is a success")
)
.catch(
(error) => res.status(500).json({error})
)
}
它正在工作,但是我很想调用一次我的数据库并编写如下代码:
It's working but I would have loved to call my db once and write something like this:
exports.modifyPresence = (req, res) => {
action.getStudentCurrentDay(req.body.hash)
.then(
dayId => {
return Day.findOneAndUpdate({_id: day.id},{$set:{present:!present}});
}
)
.then(
() => res.status(200).json("This is a success")
)
.catch(
(error) => res.status(500).json({error})
)
}
有人知道如何实现对数据库的单个调用并以一种优雅的方式切换我的布尔值吗?我不知道如何简化代码.
Do anyone knows how to implement a single call to the database and toggle my boolean in an elegant way? I have no clues how to simplify my code.
谢谢大家
推荐答案
如果使用的是MongoDB 4.2,则可以在更新语句中使用聚合运算符,例如:
If you are using MongoDB 4.2, you can use aggregation operators in your update statement, like:
.findOneAndUpdate({_id: day.id},[{$set:{present:{$eq:[false,"$present"]}}}]);
如果 present
设置为true,如果其他任何值,则将其设置为false.
That will set present
to true if it is false, and to false if it is any other value.
这篇关于使用mongoDB切换布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!