Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unique and sparse index causes duplicate error

I've got something like this:

var mongoose = require('mongoose');

mongoose.connect('mongodb://...');

var UserSchema = mongoose.Schema({
  name: {
    type: String,
    unique: true
  },
  token: {
    type: String,
    unique: true,
    sparse: true
  }
});

var User = mongoose.model('User', UserSchema);

var peter = new User();

peter.name = 'peter';
peter.token = null;

peter.save(function(err) {
  if (err) console.log(err);
  console.log('done with peter');

  var john = new User();

  john.name = 'john';
  john.token = null;

  john.save(function(err) {
    if (err) console.log(err);
    console.log('done with john');
  });

});

So peter is created first and afterwards john. However when john is saved mongoose returns the following error

{ [MongoError: E11000 duplicate key error index: node-login.users.$token_1  dup key: { :   null }]
  name: 'MongoError',
  err: 'E11000 duplicate key error index: node-login.users.$token_1  dup key: { : null }',
  code: 11000,
  n: 0,
  lastOp: 0,
  connectionId: 4527333,
  ok: 1 }

Code tried on mongolab running mongo v2.0.7 and mongoose v3.5.1.

I thought setting an index to sparse allows for multiple null values. Index is properly set as the "Indexes" tab in mongolab backend shows true for unique and sparse. Any ideas why I get the error?

like image 633
zemirco Avatar asked Mar 27 '26 05:03

zemirco


2 Answers

A sparse index only indexes the field if a document has that field. Whether the field is set to null or some other value doesn't matter, it's still checked for uniqueness if present.

So in your case, omit setting the token field at all instead of setting it to null.

like image 159
JohnnyHK Avatar answered Mar 30 '26 00:03

JohnnyHK


In JavaScript setting the value to null will not delete that property, rather it sets the value as null. In your case you should delete the token property.

delete john.token;  // In place of John.token = null

Do the same for peter.

Refer more on delete: Remove a property from a JavaScript object

like image 24
dCoder Avatar answered Mar 30 '26 02:03

dCoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!