javascript - 更新 mongodb 集合中的字段,即使它不存在

标签 javascript node.js mongodb mongoose

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

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

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

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

最佳答案

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

If the field does not exist, $set will add a new field with the specified value, provided that the new field does not violate a type constraint.

您可能会想到 upsert或其他一些递增的行为?

关于javascript - 更新 mongodb 集合中的字段,即使它不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56247503/

相关文章:

javascript - 如何在mongodb中获取更新查询WriteResult

json - 使用 ID 作为索引将数组转换为 JSON (MongoDB/Express)

javascript - 无法在 ZeroClipboard (v2.1.6) 插件中找到 $(this) 对象的父对象

javascript - 我可以在 Angular Controller 中使用插值(不仅仅是在 HTML 中)吗?

java - 如何从 Java 运行 Node.js 进程?

node.js - Aerospike - 在嵌套对象中添加新的键/值对

javascript - 为什么我的 InDesign Javascript 无法完全运行?

Javascript 取消浏览器最大化

node.js - 如何在redis中持久化HTTP响应

MongoDB 游标不返回所有文档