2014-01-24 96 views
19

如何更新如果存在,否则在javascript/node.js中插入新文档? 我收到作为函数字典的参数,如果字典包含_id应该更新,否则插入远程服务器上(我有通过猫鼬与远程服务器连接,我有我想要插入/更新的个人模式)。如何更新,如果存在,否则插入新文件?

回答

13

collection.updateupsert:true。另见here

+5

它将有更多的投票,如果它是与例 –

+5

常见问题得到共同的答案。具体问题得到具体答案。 – heinob

+1

常见答案仍然可以有具体的例子。 – aboveyou00

27

在猫鼬,你会使用Person.updateper the documentation。如果文档尚不存在,为了创建文档,您需要在选项哈希中传递{ upsert : true },因为它默认为false

Person.update({ name : 'Ted' }, { name : 'Ted', age : 50 }, { upsert : true }, callback); 
3

[db.collection.replaceOne(filter, replacement, options)]upsert:true

例如从here

try { db.restaurant.replaceOne(
      { "name" : "Pizza Rat's Pizzaria" }, 
      { "_id": 4, "name" : "Pizza Rat's Pizzaria", "Borough" : "Manhattan", "violations" : 8 }, 
      { upsert: true }  
     ); 
    } 
catch (e){ print(e); } 
相关问题