Aage Torleif
Aage Torleif

Reputation: 2013

How to create a new document 'if not exists' and return the new document with MongoDB NodeJS native driver

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') )

Upvotes: 1

Views: 796

Answers (1)

Aage Torleif
Aage Torleif

Reputation: 2013

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))

Upvotes: 1

Related Questions