0.4.4 • Published 9 years ago

mongoose-create-unique v0.4.4

Weekly downloads
571
License
MIT
Repository
github
Last release
9 years ago

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

0.4.4

9 years ago

0.4.3

9 years ago

0.4.2

10 years ago

0.4.1

10 years ago

0.4.0

10 years ago

0.3.0

10 years ago

0.2.3

10 years ago

0.2.2

10 years ago

0.2.1

10 years ago

0.2.0

10 years ago

0.1.0

10 years ago