下面是我的用户模式在user.js模型-

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;

这就是我在控制器中使用它的方式

var user = require('./../models/user.js');

这就是我在数据库中保存它的方式

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"});
    }
});

错误- - - - - -

{"name":"MongoError","code":11000,"err":"insertDocument :: caused by :: 11000 E11000 duplicate key error index: mydb.users.$email_1  dup key: { : null }"} 

我检查了db集合,没有这样的重复条目存在,让我知道我做错了什么?

供您参考- req.body.email和req.body.password是抓取值。

我也检查了这篇文章,但没有帮助

如果我完全删除,然后它插入文档,否则它抛出错误“重复”错误,即使我在local.email中有一个条目


当前回答

如果您处于开发的早期阶段:消除集合。否则:将此添加到每个给出错误的属性(注:我的英语不太好,但我尝试解释)

index:true,
unique:true,
sparse:true

其他回答

如果您处于开发的早期阶段:消除集合。否则:将此添加到每个给出错误的属性(注:我的英语不太好,但我尝试解释)

index:true,
unique:true,
sparse:true

我也遇到过类似的问题, 我只是清除特定字段的索引,然后它为我工作。 https://docs.mongodb.com/v3.2/reference/method/db.collection.dropIndexes/

检查收集索引。

我有这个问题,由于过时的索引收集字段,这应该由不同的新路径存储。

猫鼬添加索引,当你指定字段为唯一的。

转到数据库,单击该特定集合并删除除id之外的所有索引。

当我在config/models.js中进行以下配置时,我也遇到了同样的问题

module.exports.models = {
  connection: 'mongodb',
  migrate: 'alter'
}

改变迁移从'alter'到'safe'固定它为我。

module.exports.models = {
  connection: 'mongodb',
  migrate: 'safe'
}