MongoError: cannot change _id of a document MongoError: cannot change _id of a document express express

MongoError: cannot change _id of a document


From looking at your mongo error, the problem is not with mongo, it is just doing what it's supposed to do. It had an object with _id of ObjectId type: ObjectId('xxx') and now you're trying to change that object to have an _id of a String type (_id: "5083e4a7f4c0c4e270000001") and that Mongo apparently does not like.

So, the question is: why did the object have an id of type ObjectId in the first place? How did you set it the first time? If you used some other method to initialize it (I'm guessing server side), you should set the id type to be a String so that it is the same as the one coming from your script library. If you want it to stay an ObjectId, you will need to convert the String coming from your script to an ObjectId before you save it to Mongo.

HTH.


MongoDB creates _id as an ObjectID, but doesn't retrieve _id as an ObjectID.

Whether this inconsistency is 'correct behaviour' or not, it is certainly an annoying surprise for most MongoDB users.

You can fix it with:

if ( this._id && ( typeof(this._id) === 'string' ) ) {  log('Fixing id')  this._id = mongodb.ObjectID.createFromHexString(this._id)}

See MongoDB can't update document because _id is string, not ObjectId