MongoDB保存用户时电子邮件和密码无效



有一个问题,当我尝试创建新用户时,我收到以下错误:

ValidationError: User validation failed: 0.password: Path0.密码is required., 0.email: Path0.emailis required.

现在端点曾经工作过,我认为它与数据库本身有关,但我一生都不知道该怎么做。

我当然正在传递有效数据。

以下是模型和有效载荷:

import mongoose from 'mongoose';
import BaseSchema from '../utils/schema';
import bcrypt from 'bcrypt';
const userSchema = BaseSchema({
email:{
type:String,
required:true,
unique:true,
trim: true,
lowercase:true
},
password:{
type:String,
required:true
},
firstName:String,
lastName:String
});
userSchema.virtual('name').get(function(){
return `${this.firstName} ${this.lastName}`;
});
userSchema.pre('save', function(next) {
bcrypt.hash(this.password, 10, (err, hash) => {
if (err) {
return next(err);
}
this.password = hash;
next();
});
});
const User = mongoose.model('User', userSchema);
export default User;

要保存的有效负载(这是在保存之前调试的(是:

{ email: 'somevalidemail@gmail.com',
password:
'$2b$10$oQN7i5AKYDyPLp.DefeRjuyh9Z7JLayPjTO4I3B6NvytM0vq2YnVG',
firstName: 'Cool',
lastName: 'Cat' }

有人可以帮忙吗?

我认为你正在失去"这个"上下文。

userSchema.pre('save', function(next) {
var user = this;
// generate a salt
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
next();
});
});
});

最终找出了问题所在。 有两个:

  1. 基本架构(此处未列出(出现问题,字段未正确传递。
  2. 然后有一个错误:E11000 duplicate key error index: chat-app1.users.$0.email_1 dup key: { : null }'这让我相信这是一个索引问题。转储了集合索引

修复基础并清除索引后,一切再次工作

最新更新