mongoose-create-unique

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

Usage no npm install needed!

<script type="module">
  import mongooseCreateUnique from 'https://cdn.skypack.dev/mongoose-create-unique';
</script>

README

mongoose-create-unique

JS Standard Style NPM version Build Status Coveralls Status Dependency Status Downloads

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 = require('mongoose');
mongoose.plugin(require('mongoose-create-unique'));

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
Artist.createUnique(
  {name: 'Shakira'},
  {name: 'Rihanna'},
  {name: 'Shakira'}
).then(function(artists) {
  // artists[0] and artists[2] are the same  
})

License

MIT © Diego Haz