I am trying to update the document if exist or insert if not exist.I have one field with $inc,( want to increment previous value by one). My code is
var Appuser = new Appusers({
imei: req.body.imei,
$inc : {user_count:1},
install_flag : 1
});
var upsertData = Appuser.toObject();
delete upsertData._id;
Appusers.update({imei: Appuser.imei}, upsertData, {upsert: true}, function(err, data){
if(err) return console.log(err);
res.send(data);
});
Only $inc is not working. In schema i have user_count : { type:Number, default:0}
Or in other words, upsert is a combination of update and insert (update + insert = upsert). If the value of this option is set to true and the document or documents found that match the specified query, then the update operation will update the matched document or documents.
The upsert = true option creates the object if it doesn't exist. defaults to false.
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.
As the name implies, findOneAndUpdate() finds the first document that matches a given filter , applies an update , and returns the document. By default, findOneAndUpdate() returns the document as it was before update was applied. You should set the new option to true to return the document after update was applied.
You can not increase a value when it does not exists (yet). You can use $setOnInsert
to set user_count to 1 when inserting the document. Here are the docs for $setOnInsert.
Your query will look like this:
var Appuser = new Appusers({
imei: req.body.imei,
install_flag : 1
});
Appusers
.update({
imei: Appuser.imei
}, {
$set: upsertData,
$setOnInsert: {
user_count: 1
},
$inc: {
user_count:1
}
}, {
upsert: true
}, function(err, data) {
if(err) return console.log(err);
res.send(data);
});
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