javascript - Mongodb duplicate key error collection dup key : null

标签 javascript database mongodb mongoose

我正在尝试创建多个帐户。

第一个帐户总是有效,但是当我尝试创建一个新帐户时,出现以下错误:

BulkWriteError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: db.users.$friends.userid_1  dup key: { : null }

第一个用户很好,包含一个空数组的 friend ,正如我希望的那样。

但是没有创建下一个用户。

我该怎么做才能修复这个错误?

users中friends的用户schema如下:

   friends : [
    {
        userid : {type: String, default: '', unique: true },
    }
],
friendRequests: [
    {
        userid : {type: String, default: '', unique: true },
    }

编辑:

我一直在调查https://docs.mongodb.com/manual/core/index-unique/#unique-index-and-missing-field但仍然无法使其工作。

编辑2:

默认情况下,它不会创建任何好友或好友请求。

编辑3:

完整代码:

passport.use('local-signup', new LocalStrategy({
            usernameField : 'username',
            passwordField : 'password',
            passReqToCallback : true,
        },
        function(req, username, password, done) {
            process.nextTick(function() {
                console.log("doing local signup");
                username = username.toLowerCase();
                Account.findOne({username :  username }, function(err, user) {
                    var expr = "/admin/";
                    if (err) {
                        return done(err);
                    } else if (user) {
                        return done(null, false, 'That username is already taken.');
                    } else if(username.length < 3 || username.length >= 12) {
                        return done(null, false, 'Username has to be between 3 and 12 characters! :( '  + username);
                    } else if(/^[a-zA-Z0-9- ]*$/.test(username) == false) {
                        return done(null, false, 'You cant have any special characters!');
                    } else if(password.length < 5 || password.length > 15) {
                        return done(null, false, 'Password need to be 5-15 characters long!');
                    } else {

                        var newUser            = new Account();
                        newUser.username    = username;
                        newUser.password = newUser.encryptPassword(password);
                        newUser.save(function(err) {
                            if (err)
                                throw err;
                            return done(null, newUser);
                        });
                    }
                });

            });

        }));

用户模型:

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var bcrypt   = require('bcrypt-nodejs');



var UserSchema   = new Schema({
    username: {type: String, index: { unique: true }},
    password: {type: String},
    salt: { type: String},
    hash: {type: String},
    gender : {type: String, default: 'male'},
    friends : [
        {
            userid : {type: String, default: '', unique: true },
        }
    ],
    friendRequests: [
        {
            userid : {type: String, default: '', unique: true },
        }
    ]

});
UserSchema.methods.encryptPassword = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(10));
}

UserSchema.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.password);
}



module.exports = mongoose.model('Users', UserSchema);

最佳答案

comment 中所述Mongodb 不强制单个文档中数组值的唯一性。

因此您必须在客户端代码中处理数组的唯一性。您可以使用策略组合来为您处理需求。

首先去掉唯一索引,使用Mongoose unique array plugin在创建/更新文档时让 mongoose 检查数组中的唯一性。

该插件适用于标量和文档数组。对于您的情况,您可以进行以下更改。

var uniqueArrayPlugin = require('mongoose-unique-array');
UserSchema.plugin(uniqueArrayPlugin);

这将通过验证器强制执行验证,并应在您执行更新/保存操作时向您显示验证消息。

如博客中所述,当您在更新查询中使用 $push 时,独特的插件不起作用。

你可以使用

Account.findOne({"friends.userid":{"$ne":inputuserid}}, {"$push":{"friends":new user doc}});

阅读blogusage examples从作者那里获取更多信息。

关于javascript - Mongodb duplicate key error collection dup key : null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48807435/

相关文章:

javascript - 使用 JavaScript 正则表达式的建议

javascript - 将对象值作为键值对导入

python - 如何在给定的时间间隔内随机调用一个函数? - Python

mongodb - 错误 : mongodb. jdbc.MongoDriver 未加载。你确定你已经包含了正确的 jdbc 驱动程序

javascript - 为什么主干 View 会触发更改事件两次?

c# - 举办锦标赛,如何存储所有玩家分数

ruby-on-rails - 在 >= Rails 3.2.0 中创建 "test"数据库内容的最佳方法是什么?

ruby - 使用 MongoMapper 根据数组的大小在 MongoDB 中排序项目?

node.js - 用变量值替换属性nodeJS

javascript - 解析 JSON 流