1

I want to create a new document if it doesn't exist and return the new document once created, however if the document already exists I would like an exception to be thrown.

I think the way I am doing this seems hackish, is there a better means of doing this?

var query = { name: 'guaranteed to be unique' }
var new_doc = { ... }
var col = // the Mongo collection we're using

col.updateOne(
    query,
    new_doc,
    {upsert: true}
)
.then(update => col.findOne({_id, update.result.upserted.pop()._id}))
.then(doc => console.log(doc))
.catch( exception => console.log('that already exists') )
Aage Torleif
  • 1,907
  • 1
  • 20
  • 37

1 Answers1

1

After a lot a searching I found some answers in this post, but here's a clean example with findOneAndUpdate and the returnOriginal property set false

col.findOneAndUpdate(
    query,
    new_doc,
    { upsert: true, returnOriginal:false }
)
.then(update => update.value)
.then(doc => console.log(doc))
Community
  • 1
  • 1
Aage Torleif
  • 1,907
  • 1
  • 20
  • 37
  • Be aware that any properties in `new_doc` will overwrite the properties in the database if the document already exists. – robertklep Jun 20 '16 at 20:11