node.js - "Path ' hashed_pa​​ssword ' is required"即使使用虚拟字段时 hash_password 字段已满

标签 node.js mongodb mongoose validationerror

我正在尝试创建一个应用程序,其中密码被发送到虚拟字段中,然后进行哈希处理并存储为哈希值。但是我不断收到此错误:

(node:32101) UnhandledPromiseRejectionWarning: ValidationError: User validation failed: hashed_password: Path `hashed_password` is required.

下面是我的代码,当我运行它时,我会得到代码下面包含的日志。

const mongoose = require('mongoose');
const uuidv1 = require('uuid/v1');
const cryptop = require('crypto');

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        trim: true,
        required: true
    },
    email: {
        type: String,
        trim: true,
        required: true
    },
    hashed_password: {
        type: String,
        required: true
    },
    salt: String,
    created: {
        type: Date,
        default: Date.now
    },
    updated: Date
});

userSchema
    .virtual("password")
    .set(password => {
        // create temporary variable called _password
        this._password = password;
        // generate a timestamp
        this.salt = uuidv1();
        // encryptPassword()
        this.hashed_password = this.encryptPassword(password);
        console.log(this);
    })
    .get(function () {
        return this._password;
    });

userSchema.methods = {
    encryptPassword: password => {
        if (!password) return "";
        try {
            return crypto
                .createHmac("sha1", this.salt)
                .update(password)
                .digest("hex");
        } catch (err) {
            return "";
        }
    }
};

module.exports = mongoose.model("User", userSchema);

错误:

Express is listening on port 8080
DB connected
{ name: 'Ryan', email: 'ryan1@gmail.com', password: 'rrrrr' }
(node:32477) UnhandledPromiseRejectionWarning: TypeError: this.encryptPassword is not a function

当我在没有 encryptPassword 函数的情况下执行此操作时,我仍然收到错误:

const mongoose = require('mongoose');
const uuidv1 = require('uuid/v1');
const cryptop = require('crypto');

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        trim: true,
        required: true
    },
    email: {
        type: String,
        trim: true,
        required: true
    },
    hashed_password: {
        type: String,
        required: true
    },
    salt: String,
    created: {
        type: Date,
        default: Date.now
    },
    updated: Date
});

userSchema
    .virtual("password")
    .set(password => {
        // create temporary variable called _password
        this._password = password;
        // generate a timestamp
        this.salt = uuidv1();
        // encryptPassword()
        // this.hashed_password = this.encryptPassword(password);
        this.hashed_password = 'Test hash';
        console.log(this);
    })
    .get(function () {
        return this._password;
    });

userSchema.methods = {
    encryptPassword: password => {
        if (!password) return "";
        try {
            return crypto
                .createHmac("sha1", this.salt)
                .update(password)
                .digest("hex");
        } catch (err) {
            return "";
        }
    }
};

module.exports = mongoose.model("User", userSchema);

错误:

Express is listening on port 8080
DB connected
{ name: 'Ryan', email: 'ryan1@gmail.com', password: 'rrrrr' }
{
  _password: 'rrrrr',
  salt: 'ff790ca0-34f0-11ea-9394-a53427d4f6bb',
  hashed_password: 'Test hash'
}
(node:32577) UnhandledPromiseRejectionWarning: ValidationError: User validation failed: hashed_password: Path `hashed_password` is required.

最佳答案

尝试使用function(password)而不是password =>

当您使用箭头函数时,this 并不是指您正在保存的用户,这也是您在控制台登录时看不到姓名和电子邮件的原因。

关于node.js - "Path ' hashed_pa​​ssword ' is required"即使使用虚拟字段时 hash_password 字段已满,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59700861/

相关文章:

node.js - 为什么在聊天应用程序中使用 redis?

node.js - 将 Git 存储库迁移到 tfs Git,同时保留所有历史提交

node.js - 当mongodb不在同一个VM中时,mongodb连接超时

node.js - 在 Mongoose 中清理用户输入

mongodb序列化子集结果

javascript - 如何将每个对象都有一个元素数组的对象列表转换为具有子元素作为属性的对象数组

node.js - 使用 Mongoose 异步保存多个文档

ruby-on-rails - 将带有 React 组件的 Ruby on Rails 项目部署到 Heroku

node.js - Express js Mongoose 替代 MySQL % 通配符

mongodb - 将日期与mongodb中的月份或年份进行比较