Доброй ночи, не могу отловить баг. Создаю юзера, но получаю ошибку :
{
"name": "MongoError",
"message": "E11000 duplicate key error collection: Udemy.users index: UserSchema.email_1 dup key: { : null }",
"driver": true,
"index": 0,
"code": 11000,
"errmsg": "E11000 duplicate key error collection: Udemy.users index: UserSchema.email_1 dup key: { : null }"
}
Код : User.js
const mongoose = require('mongoose');
const validator = require('validator');
const jwt = require('jsonwebtoken');
const _ = require('lodash');
let UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
trim: true,
minlength: 1,
unique: true,
validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email'
}
},
password: {
type: String,
require: true,
minlength: 6
},
tokens: [{
access: {
type: String,
required: true
},
token: {
type: String,
required: true
}
}]
});
UserSchema.methods.toJSON = function () {
let user = this;
let userObject = user.toObject();
return _.pick(userObject, ['_id', 'email']);
};
UserSchema.methods.generateAuthToken = function () {
let user = this;
let access = 'auth';
let token = jwt.sign({_id: user._id.toHexString(), access}, 'abc123').toString();
user.tokens = user.tokens.concat([{access, token}]);
return user.save().then(() => {
return token;
});
};
let User = mongoose.model('User', UserSchema);
module.exports = {
User
};
server.js :
app.post('/users', (req, res) => {
let body = _.pick(req.body, ['email', 'password']);
let user = new User(body);
user.save().then(() => {
return user.generateAuthToken();
}).then((token) => {
res.header('x-auth', token).send(user);
}).catch((e) => {
res.status(400).send(e);
})
});
Полный код тут
Спасибо!