如果存在,如何更新否则插入新文档? [英] How to update if exists otherwise insert new document?

查看:33
本文介绍了如果存在,如何更新否则插入新文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果存在,如何更新,否则在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆