Sometimes I need a document to exist in the DB, and am happy to either work with the existing document, or create the document if it's missing, and work with the new one.
This seems like a fairly common use case, but I've looked through the Mongoose docs and I can't find anything.
Mongoose Collection methods like findOneAndUpdate()
and update()
with upsert: true
are about modifying documents - I don't wish to modify the document if it exists, just get a reference to it.
Example: (added for @neillunn) I want to add a User with a reference to a Company whose 'name' is 'foo'. Before that, I'd like to lookup a Company with {name: 'foo'}
and create that if it doesn't exist.
Example 2: (added for @neillunn) code I'm using now to handle the example scenario:
// Find or create an an instance and return a cb with a reference to it.
var findOrCreate = function(model, criteria, cb){
model.update(criteria, criteria, {upsert: true}, function(err, numberAffected, raw){
if ( ! raw.updatedExisting ) {
console.log('Created instance')
} else {
console.log('Found existing instance')
}
model.findOne(criteria, cb)
})
}
Note: findOneAndUpdate()
won't work because it will try and modify the existing document, and get a 'duplicate key error index'
The find() function is used to find particular data from the MongoDB database. It takes 3 arguments and they are query (also known as a condition), query projection (used for mentioning which fields to include or exclude from the query), and the last argument is the general query options (like limit, skip, etc).
Return value The returned value could be an array of documents, a single document if it matches only one, or an empty array if no document is matched.
As the name implies, findOneAndUpdate() finds the first document that matches a given filter , applies an update , and returns the document. By default, findOneAndUpdate() returns the document as it was before update was applied. You should set the new option to true to return the document after update was applied.
Mongoose queries are not promises. They have a . then() function for co and async/await as a convenience.
As stated in the comments, there is a plugin for mongoose that does this: http://github.com/drudge/mongoose-findorcreate
This Thread also describes a way to achieve this without plugin. Im just not sure though if it works with mongoose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With