如果存在,如何更新否则插入新文档?

编程入门 行业动态 更新时间:2024-10-22 16:46:30
本文介绍了如果存在,如何更新否则插入新文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

如果存在,如何更新否则插入新文档?

本文发布于:2023-11-28 10:10:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641978.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!