How to update if exists otherwise insert new document?

前端 未结 4 1838
执笔经年
执笔经年 2020-12-02 20:14

How to update if exists otherwise insert new document in javascript/node.js? I am getting as parameter to function dictionary,if dictionary contains _id should update, othe

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 20:37

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

    E.g. from 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); }
    

提交回复
热议问题