小编jaw*_*g35的帖子

Mongoose pre save使用了不正确的"this"上下文?

任何人都可以弄清楚下面我的代码有什么问题吗?

从文档中看起来this,Mongoose .pre('save')方法应该是模型本身,但在下面的代码中this最终成为一个空对象.

const Mongoose = require('./lib/database').Mongoose;
const Bcrypt = require('bcrypt');

const userSchema = new Mongoose.Schema({
    email: { type: String, required: true, index: { unique: true } },
    password: { type: String, required: true }
});

userSchema.pre('save', (next) => {

    const user = this;

    Bcrypt.genSalt((err, salt) => {

        if (err) {
            return next(err);
        }

        Bcrypt.hash(user.password, salt, (err, encrypted) => {

            if (err) {
                return next(err);
            }

            user.password = encrypted;
            next();
        });
    });
});

const User …
Run Code Online (Sandbox Code Playgroud)

javascript mongoose mongodb node.js ecmascript-6

4
推荐指数
2
解决办法
1964
查看次数

标签 统计

ecmascript-6 ×1

javascript ×1

mongodb ×1

mongoose ×1

node.js ×1