代码之家  ›  专栏  ›  技术社区  ›  Jony-Y

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

  •  1
  • Jony-Y  · 技术社区  · 8 年前

    ValidationError: User validation failed: 0.password: Path 0.密码 is required., 0.email: Path is 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' }
    

    2 回复  |  直到 8 年前
        1
  •  0
  •   scetiner    8 年前

    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();
            });
        });
    });
    
        2
  •  0
  •   Jony-Y    8 年前

    结果发现了问题。

    1. 当时出现了一个错误: E11000 duplicate key error index: chat-app1.users.$0.email_1 dup key: { : null }'