Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upsert with Mongoskin (node.js and mongodb)

I'm learning node.js and mongodb. I'm using the mongoskin module in my app, but I can't seem to get "upsert" functionality to work.

I've read the (rather opaque) mongoskin guide on github. Here's what I've tried so far:

// this works.  there's an insert then an update.  The final "x" is "XX".
db.collection("stuff").insert({a:"A"}, {x:"X"});
db.collection("stuff").update({a:"A"}, {x:"XX"});

// this does NOT work.  I thought it would do an upsert, but nothing.
db.collection("stuff").update({b:"B"}, {y:"YY"}, true);

How can I create "update or insert if not exists" functionality?

like image 786
Sir Robert Avatar asked Apr 28 '12 20:04

Sir Robert


People also ask

What is Upsert in node JS?

In MongoDB, an upsert means an update that inserts a new document if no document matches the filter . To upsert a document in Mongoose, you should set the upsert option to the Model. updateOne() function: const res = await Character.

Can we connect MongoDB with node js?

To connect a Node. js application to MongoDB, we have to use a library called Mongoose. mongoose. connect("mongodb://localhost:27017/collectionName", { useNewUrlParser: true, useUnifiedTopology: true });

What is Upsert in mongoose?

Upsert is a combination of insert and update (inSERT + UPdate = upsert). We can use the upsert with different update methods, i.e., update, findAndModify, and replaceOne. Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter.


1 Answers

I've not tried it, but according to the doc here: https://github.com/guileen/node-mongoskin#inherit-updating and here: https://github.com/christkv/node-mongodb-native/blob/master/docs/insert.md, it looks like options is the third parameter, and it's supposed to be an object, like so:

db.collection("stuff").update({b:"B"}, {y:"YY"}, {upsert:true});
like image 132
Eve Freeman Avatar answered Oct 25 '22 21:10

Eve Freeman