使用 mongoDB 切换布尔值 [英] Toggle a boolean value with mongoDB
问题描述
我正在使用 mongoDB 数据库,我想切换 Day 对象内的布尔存在属性.这是我的工作代码:
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
为 false,则将其设置为 true,如果为任何其他值,则设置为 false.
That will set present
to true if it is false, and to false if it is any other value.
这篇关于使用 mongoDB 切换布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!