Mongoose plugin to create a document or return the existing one based on the unique index

Downloads in past


310.4.47 years ago8 years agoMinified + gzip package size for mongoose-create-unique in KB


!JS Standard Stylestandard-imagestandard-url !NPM versionnpm-imagenpm-url !Build Statustravis-imagetravis-url !Coveralls Statuscoveralls-imagecoveralls-url !Dependency Statusdepstat-imagedepstat-url !Downloadsdownload-badgenpm-url
Mongoose plugin to create a document or return the existing one based on the unique index


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: myfield1 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.


var mongoose = require('mongoose');

var ArtistSchema = new mongoose.Schema({
  name: {
    type: String,
    unique: true

var Artist = mongoose.model('Artist', ArtistSchema);

Artist.createUnique({name: 'Shakira'}).then(function(artist) {
  console.log(artist); // {_id: 1, name: 'Shakira'}
  return Artist.createUnique({name: 'Rihanna'});
}).then(function(artist) {
  console.log(artist); // {_id: 2, name: 'Rihanna'}
  return Artist.createUnique({name: 'Shakira'});
}).then(function(artist) {
  console.log(artist); // {_id: 1, name: 'Shakira'}

// or multiple
  {name: 'Shakira'},
  {name: 'Rihanna'},
  {name: 'Shakira'}
).then(function(artists) {
  // artists[0] and artists[2] are the same  


MIT © Diego Haz