Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoError: Mod on _id not allowed

There are a few questions out there on this but I can't seem to find a solution that seems to be the accepted approach at the moment.

I'm trying to update a document in MongoDB and I'm using Mongoosejs to do it. However, I'm getting this error:

{ [MongoError: Mod on _id not allowed]
  name: 'MongoError',
  lastErrorObject:
   { err: 'Mod on _id not allowed',
     code: 10148,
     n: 0,
     connectionId: 35,
     ok: 1 },
  ok: 0,
  errmsg: 'Mod on _id not allowed' }

The code I'm using to make the update is:

app.put('/task/:short', auth, function (req, res) {
  Task.findOneAndUpdate({short:req.params.short}, req.body, function(err, task) {
    if(err) console.log(err);
    res.json(200, {content: task});
  })
});

because I had a "field" called "short_id" I thought it might be an issue with having a "_id" part to the field name so I changed it to "short" but still no luck - I get the same error. I've later discovered that it thinks I'm trying to change the _id field but I don't why.

like image 973
tommyd456 Avatar asked Jun 08 '14 07:06

tommyd456


3 Answers

The problem was because I was using short (which is unique) to find the document and update it and _id was being sent as a value to update which can't be done.

Therefore, before sending the params I deleted the _id from the object.

delete the_object._id

and everything now works.

like image 126
tommyd456 Avatar answered Oct 22 '22 03:10

tommyd456


If you are using lodash, the following code can help..

var id = update._id;
var update = _.omit(update,'_id');
mongo.mCustomers.findOneAndUpdate({_id:id},update,callback);
like image 7
Koder Avatar answered Oct 22 '22 02:10

Koder


I had tests passing locally on MongoDB 3.x, but I was getting this error in CircleCI (a continuous integration service) which runs an old version (2.4.x)

Turns out installing a newer version fixed the issue I was having.

like image 4
Pier-Luc Gendreau Avatar answered Oct 22 '22 02:10

Pier-Luc Gendreau