Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose update : $inc is not working in upsert

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}

like image 921
Ammar Hayder Khan Avatar asked Aug 25 '15 07:08

Ammar Hayder Khan


People also ask

How do you update Upsert?

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.

What is Upsert true in mongoose?

The upsert = true option creates the object if it doesn't exist. defaults to false.

What is Upsert in update MongoDB?

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.

How do I use Find ID and update?

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.


1 Answers

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);
    });
like image 190
Thomas Bormans Avatar answered Oct 04 '22 17:10

Thomas Bormans