0

I'm referring to the Mongo Node driver's findOneAndReplace method.

Two questions:

  1. Is it true that you can't pass a replacement object with an _id property? It wasn't working when I was passing that property, and started working when I removed the property.

  2. When the object gets replaced in the database, what will the _id of the new object be? For me it seems that it's the same as the old _id, but I'm not sure if there are situations where this won't be the case.

Adam Zerner
  • 17,797
  • 15
  • 90
  • 156

1 Answers1

2
  1. This is true, this is a fundamental design property of MongoDB. You cannot, for reasons of sharding and what not, change the _id in the document. You must replace the document, for reference: How update the _id of one MongoDB Document?

  2. The same as the old _id, the _id never changes in a document.

Community
  • 1
  • 1
Sammaye
  • 43,242
  • 7
  • 104
  • 146
  • I have a tangential question that I'm curious about - how does 2) work? I thought that it's actually creating a new document, and that when new documents are created it generates some `_id` that has never been used before. – Adam Zerner Jul 27 '15 at 22:21
  • @AdamZerner it doesn't create a new document it updates the old one with new contents. Even when you replace the contents of the document you don't actually replace the document. It is a bit deceptive I know but the _id is a constant within any document – Sammaye Jul 27 '15 at 23:15
  • @AdamZerner Ok I just double checked a sec and "replace" is a really bad word to use here. It is mega confusing but after reading the documentation is essentially FindAnyModify but it replaces the contents of the document excluding _id since MongoDB does not allow that. There is an upsert option in the function for upserting a new document but otherwise it will not replace the actual document with a new _id – Sammaye Jul 27 '15 at 23:17