node.js - E11000 duplicate key error index in mongodb mongoose -
following user
schema in user.js
model -
var userschema = new mongoose.schema({ local: { name: { type: string }, email : { type: string, require: true, unique: true }, password: { type: string, require:true }, }, facebook: { id : { type: string }, token : { type: string }, email : { type: string }, name : { type: string } } }); var user = mongoose.model('user',userschema); module.exports = user;
this how using in controller -
var user = require('./../models/user.js');
this how saving in db -
user({'local.email' : req.body.email, 'local.password' : req.body.password}).save(function(err, result){ if(err) res.send(err); else { console.log(result); req.session.user = result; res.send({"code":200,"message":"record inserted successfully"}); } });
error -
{"name":"mongoerror","code":11000,"err":"insertdocument :: caused :: 11000 e11000 duplicate key error index: mydb.users.$email_1 dup key: { : null }"}
i checked db collection , no such duplicate entry exists, allow me know doing wrong ?
fyi - req.body.email
, req.body.password
fetching values.
i checked post no help stack link
edit
if removed inserts document, otherwise throws error "duplicate" error have entry in local.email
the error message saying there's record null
email. in other words, have user without email address.
the relevant documentation this:
if document not have value indexed field in unique index, index store null value document. because of unique constraint, mongodb permit 1 document lacks indexed field. if there more 1 document without value indexed field or missing indexed field, index build fail duplicate key error.
you can combine unique constraint sparse index filter these null values unique index , avoid error.
unique indexes
sparse indexes contain entries documents have indexed field, if index field contains null value.
in other words, sparse index ok multiple documents having null
values.
sparse indexes
node.js mongodb express mongoose mean-stack
No comments:
Post a Comment