Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update if exists otherwise insert new document?

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).

like image 494
PaolaJ. Avatar asked Jan 24 '14 21:01

PaolaJ.


People also ask

Which of the following will you use to insert a new document or update an existing document in a collection in Javascript?

insert() method is used to add or insert new documents into a collection in your database.

Does MongoDB Update create if not exists?

You can use upsert i.e. whenever you insert a value and it already exist then update would be performed. If the value does not already exist then it would get inserted.

Is there an Upsert option in the MongoDB insert command?

Since upsert is defined as operation that "creates a new document when no document matches the query criteria" there is no place for upserts in insert command.

What is Upsert MongoDB?

In MongoDB, upsert is a method that is used to insert and update the value in any operation. In other words, the MongoDB upsert method is a combination of insert and update (insert + update = upsert). By default, the upsert method's value is always false.

How to create a document if it doesn't already exist?

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 ); update is deprecated. Use updateOne, updateMany, or bulkWrite instead.

What is if exists else update in SQL Server 2019?

If that record already exists then, the stored procedure will update that record. And if the record does not exist then, it will insert the record in the table. So, in this tutorial, we will understand how to create a stored procedure for if exists else update operation in SQL Server 2019. And we will also try to demonstrate multiple examples.

How to use output parameters in a stored procedure for insert/update?

Now, let’s see how we can use output parameters in the stored procedure for insert and update operation. The OUTPUT parameter in a stored procedure is used to return data from the stored procedure to the caller or user. And in this case, we can use this output parameter to determine whether an insert or update statement is executed.


1 Answers

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.

i.e.

Person.update( { name : 'Ted' }, { name : 'Ted', age : 50 }, { upsert : true }, callback ); 
like image 179
EmptyArsenal Avatar answered Oct 18 '22 17:10

EmptyArsenal