【问题标题】:Toggle a boolean value with mongoDB使用 mongoDB 切换布尔值
【发布时间】:2021-04-03 23:46:38
【问题描述】:

我正在使用 mongoDB 数据库,我想切换 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 optimization boolean toggle


    【解决方案1】:

    如果您使用的是 MongoDB 4.2,则可以在更新语句中使用聚合运算符,例如:

    .findOneAndUpdate({_id: day.id},[{$set:{present:{$eq:[false,"$present"]}}}]);
    

    如果 present 为 false,则将其设置为 true,如果为任何其他值,则设置为 false。

    【讨论】:

      【解决方案2】:

      您可以从 MongoDB v4.2 开始使用update with aggregation pipeline

      • $not 计算一个布尔值并返回相反的布尔值;即,当传递一个计算结果为 true 的表达式时,$not 返回 false;当传递一个计算结果为 false 的表达式时,$not 返回 true。
      return Day.findOneAndUpdate(
        { _id: day.id },
        [
          { $set: { present: { $not: "$present" } } }
        ]
      );
      

      Playground

      【讨论】:

      • 如果 present 字段不包含布尔值,这也会产生不修改的效果。我不知道提问者的意图。
      • 是的,你是对的 $not 评估为 false 以下:null0undefined 值和其他为 true。您的答案确实是准确的解决方案。实际上我看起来重复了question,我投票赞成关闭并将这个问题称为重复。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 2017-08-05
      • 1970-01-01
      • 2017-09-27
      • 2021-02-24
      • 2012-07-21
      • 2011-06-03
      相关资源
      最近更新 更多