Update a collection where _id document is an ObjectId didn't work


#1

I have this document:

{ “_id” : ObjectId(“57a8963c6675fe82c76345d0”), “numberOfClick” : 0 }

I want to update numberOfClick field by increment it. My code’s like :

MyCollection.update({’_id’ : x }, {’$set’:{ numberOfClick : inc }});

“x” is a string “57a8963c6675fe82c76345d0” and “inc” is the number incremented by 1.
Did I miss something ?


#2

A couple of small issues:

  1. Since your stored document is using a Mongo ObjectId for its primary key, instead of a string based ID, you need to accommodate for this when you run your update.

  2. You might want to use the Mongo $inc operator instead.

An updated example:

MyCollection.update({ 
  _id: new Mongo.ObjectID(x) 
}, { 
  $inc: { 
    numberOfClicks: 1
  }
});