Reputation: 7378
I have a web service that gets an object from mongodb, displays it as json, allows the user to edit the object then save the object back. I am trying to implement a "Save as" button to post allow the user to make changes to the object and then save it back as a new object. The problem is since the objectId is not changing when I do the POST request the object just overwrites the preexisting object with the same objectId.
Is there a way to assign a new objectId in javascript?
The implementation is done with the mongodb c# driver on a wcf service.
Upvotes: 0
Views: 629
Reputation: 222461
No you can not change or remove the _id
field from the mongodb document. This is because _id
serves as a primary key and therefore is immutable. If you really want to change the _id of the document, you need to remove this document and copy it's content to a new one with the new _id
.
P.S. I am talking here about _id field. If you want to change any other field, which for some reason happened to have ObjectId data, you can do this.
Upvotes: 0
Reputation: 69663
You could attempt to replicate the algorithm which is used for ObjectID generation, but there is an easier way to do that. When you just remove the _id from the document, MongoDB will create a new one and save it under this. You can do this with the javascript delete keyword:
delete yourDocument._id;
Alternatively you can do it on the C# side by generating a new _id for the document before you save it:
yourDocument.Set("_id", ObjectId.GenerateNewId());
Upvotes: 1