I need to set up multiple user accounts.
The first account creation is successful, but I encounter an error when trying to create a new account:
BulkWriteError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: db.users.$friends.userid_1 dup key: { : null }
The initial user's details are correct, with an empty array for friends as intended.
However, I encounter issues when creating subsequent users.
How can I resolve this error?
The section of the user schema related to friends in users is as follows:
friends : [
{
userid : {type: String, default: '', unique: true },
}
],
friendRequests: [
{
userid : {type: String, default: '', unique: true },
}
EDIT:
I have referred to https://docs.mongodb.com/manual/core/index-unique/#unique-index-and-missing-field but have not been able to resolve the issue.
EDIT2:
There are no friends or friend requests created by default.
EDIT3:
Here is the complete code:
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);
});
}
});
});
}));
User Model:
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);