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?
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.
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 });
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.
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With