1

im having issues finding an atomic method for finding a single object in MongoDB and creating it with some preset values if it doesn't exist yet. I found a thread (MongoDB atomic "findOrCreate": findOne, insert if nonexistent, but do not update) but the method findAndModify is deprecated and it seems to me that findOneAndUpdate always updates the object, therefore resetting all my data when an object is found, rather than just returning the found one without changing it.

Thanks in advance, i've searched a lot but didn't find anything that helped me.

1 Answers1

0

Look at the upsert option, normally it create the document if it canno't find it

Nicolas
  • 457
  • 5
  • 15
  • yes thats what i need, but as far as i see correctly it always upserts/modifies the object, even if it exists. That's not what i want though, i just want to find it without changing anything while making sure it exists – Sebastian Di Luzio Mar 27 '18 at 13:31
  • The `upsert` option is defined to create a new document if the filter don't match any documents. So if it already exist, it will update your document, not create a new one, except if your filter is bad – Nicolas Mar 27 '18 at 13:35
  • yeah thats exactly why the method doesn't work for me and im looking for one that works. i **dont** want it to change anything if it exists – Sebastian Di Luzio Mar 27 '18 at 13:37
  • So I don't understand the problem. You want to find a document and create it if it doesn't already exist right ? – Nicolas Mar 27 '18 at 13:40
  • oh okay i now see that $setoninsert should take care that it doesn't chnage the object if it doesnt create it using findeOneAndUpdate, so using `let result = await db.collection("users").findOneAndUpdate({_id:userid}, {$setOnInsert:{ warnings: 0, bans: 0, kicks: 0, botusage: 0, sound: false }}, {returnNewDocument:true, upsert:true}); ` should do the trick? – Sebastian Di Luzio Mar 27 '18 at 13:51
  • yeah i just needed to work around the weirdness that their node.js methods use differently named tags in the options than in their documentation and then it worked thanks for sticking with me – Sebastian Di Luzio Mar 27 '18 at 15:15