如果存在则如何更新,否则插入新文件? [英] How to update if exists otherwise insert new document?
问题描述
如何更新(如果存在),否则在javascript/node.js中插入新文档? 我正在获取函数字典的参数,如果字典中包含_id的字典应该更新,否则插入到远程服务器上(我通过mongoose与远程服务器建立了连接,并且我想插入/更新Person模式).
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, otherwise insert on remote server (I have connection with remote server through mongoose and I have Person schema which I want to insert/update).
推荐答案
在Mongoose中,您将使用Person.update
根据文档.为了创建尚不存在的文档,您需要在选项哈希中传递{ upsert : true }
,因为它默认为false
.
In Mongoose, you'd use Person.update
per the documentation. In order to create a document if it doesn't already exist, you need to pass { upsert : true }
in the options hash as it defaults to false
.
即
Person.update( { name : 'Ted' }, { name : 'Ted', age : 50 }, { upsert : true }, callback );
这篇关于如果存在则如何更新,否则插入新文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!