如何在mongo db es6中调用预钩子?

时间:2018-12-03 09:31:59

标签: node.js mongoose ecmascript-6

我想在将MongoDB保存到数据库之前调用它。我正在使用nodejs和es6类。你能告诉我我错了吗。请告诉我定义类的正确方法。

import mongoose from '../db/db'
import bcrypt from 'bcrypt-nodejs';

let SALT_WORK_FACTOR = 10;


class UserProfile {
userProfile

constructor() {
    let userSchema = new mongoose.Schema({
        userId: {
            type: String,
            required: true
        },
        email: {
            type: String,
            unique: true,
            index: true,
            lowercase: true,
            required: [true, 'email field is Required']
        },
        password: {
            type: String,
            required: [true, 'password field is Required'],
            validate: [function (v) {
                return v.length >= 8;
            }, 'Password min length is 8 chars']
        },
        created: {
            type: Date,
            default: Date.now
        },

        aliasesCount: {
            type: Number,
            default: 0
        }
    });

    userSchema.pre((next) => {
       console.log('here')
        let user = this;
        console.log(user);
        if (!user.isModified('password'))
            return next();

        bcrypt.genSalt(SALT_WORK_FACTOR, function (err, salt) {
            if (err)
                return next(err);
            bcrypt.hash(user.password, salt, null, function (err, hash) {
                if (err)
                    return next(err);

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

    this.userProfile = mongoose.model('User', userSchema);
}

}


export default new UserProfile().userProfile

但是prehook没有打电话,而且唯一的电子邮件也无法正常工作。我正在使用mongo图集云。

0 个答案:

没有答案