【问题标题】:Update a field in mongodb collection even if it doesnt exist更新 mongodb 集合中的字段,即使它不存在
【发布时间】:2019-05-22 09:33:15
【问题描述】:

我想将isChecked字段设置为mongodb集合,即使集合中不存在该字段:

User.updateOne({ id }, { $set: { isChecked: true } });

但它不会更新,因为isChecked 不存在。我记得是new,但我记不太清了。

附:我喜欢 mongodb,但我讨厌它的文档。 0 可读性

【问题讨论】:

  • 对我来说,即使该字段不存在,它也可以工作。 User.updateOne({ id }, { $set: { isChecked: true } })

标签: javascript node.js mongodb mongoose


【解决方案1】:

此查询的行为不应取决于isChecked 是否存在; $set 运算符将设置 isCheckedregardless of if the field exists in the document before or not 的值:

如果该字段不存在,$set 将添加一个新字段 指定值,前提是新字段不违反类型 约束。

您是否可能在考虑upsert 或其他一些递增的行为?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-19
    • 2021-05-21
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多