首页 > 解决方案 > 即使集合不存在使用 node.js 和 mongoose 更新 Mongo DB 中的数据

问题描述

我需要更新一个存在与否的字段:我试过这个

db.foo.update(
    { site: '"wisdom'},
    { $set: {'club': 'fc barcelona'}}, (upsert=true)
)

标签: javascriptnode.jsreactjsmongodbexpress

解决方案


您可以使用 mongodb 的 upsert:true 选项。基本上,如果查询字符串与文档匹配或不匹配,则它会更新文档,然后基本上创建它。默认情况下,它的值设置为 false。

db.foo.update(
  { site_id: "xxx" },
  { $set: { "title.de": "", "content.de": "" } },
  {upsert: true}
);

参考:https ://docs.mongodb.com/manual/reference/method/db.collection.update/


推荐阅读