使用mongoDB切换布尔值
我正在使用mongoDB数据库,我想在Day对象内切换boolean present属性。这是我的工作代码:使用mongoDB切换布尔值,mongodb,optimization,boolean,toggle,Mongodb,Optimization,Boolean,Toggle,我正在使用mongoDB数据库,我想在Day对象内切换boolean present属性。这是我的工作代码: exports.modifyPresence = (req, res) => { action.getStudentCurrentDay(req.body.hash) .then( dayId => { return Day.findOne({_id: dayId}); } ) .then( day => {
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})
)
}
它正在工作,但我很想给我的数据库打一次电话,然后写下如下内容:
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})
)
}
有人知道如何实现对数据库的单个调用并以优雅的方式切换布尔值吗?我不知道如何简化我的代码
谢谢大家如果您使用的是MongoDB 4.2,您可以在更新语句中使用聚合运算符,如:
.findOneAndUpdate({_id: day.id},[{$set:{present:{$eq:[false,"$present"]}}}]);
这会将
present
设置为true(如果为false),并将其设置为false(如果为任何其他值)。如果您使用的是MongoDB 4.2,则可以在update语句中使用聚合运算符,如:
.findOneAndUpdate({_id: day.id},[{$set:{present:{$eq:[false,"$present"]}}}]);
如果设置为false,则将present
设置为true;如果设置为任何其他值,则将设置为false。您可以从MongoDB v4.2开始使用
- 计算布尔值并返回相反的布尔值;i、 e.当传递一个计算结果为true的表达式时,
返回false;当传递一个计算结果为false的表达式时,$not
返回true$not
- 计算布尔值并返回相反的布尔值;i、 e.当传递一个计算结果为true的表达式时,
返回false;当传递一个计算结果为false的表达式时,$not
返回true$not
此更新是否仍然是原子更新?此更新是否仍然是原子更新?如果不包含布尔值,则此更新也不会修改
present
字段。我不知道询问者的意图是什么。是的,你是对的。$not
评估为false,如下:null
,0
,和未定义的值和其他为true。你的答案真的很准确。实际上,我看起来是重复的,我投票赞成关闭,并将此问题称为重复。如果present
字段不包含布尔值,则这也不会修改该字段。我不知道询问者的意图是什么。是的,你是对的。$not
评估为false,如下:null
,0
,和未定义的值和其他为true。你的答案真的很准确。实际上,我看起来是重复的,我投票赞成结束,并把这个问题称为重复。