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?
A sparse index only indexes the field if a document has that field. Whether the field is set to
nullor some other value doesn’t matter, it’s still checked for uniqueness if present.So in your case, omit setting the
tokenfield at all instead of setting it tonull.