mongoose-create-unique
Mongoose plugin to create a document or return the existing one based on the unique index
Install
npm install --save mongoose-create-unique
It works with MongoDB 3.0 or higher.
The problem
If you try to create a document with a duplicate key, MongoDB and Mongoose will throw the following error:
E11000 duplicate key error collection: mydb.mycollection index: myfield_1 dup key: { : "my value" }'
We want to avoid this error when creating a new document with unique field by returning the existing one.
How it works
It was designed to work the same way Model.create
and Model#save
do. Just use Model.createUnique
and Model#saveUnique
instead. The only difference is that it will return the existing document(s) if there is already one, not an error.
What mongoose-create-unique
actually does is try to save the document(s). If Mongo throw the duplicate key error, it finds the existing document and returns it.
Example
var mongoose = ;mongoose; var ArtistSchema = name: type: String unique: true ; var Artist = mongoose; Artist; // or multipleArtist
License
MIT © Diego Haz