sequelize 模型方法 "this" 问题

sequelize model methods "this" issue

我对使用 sequelize 的用户 JWT 有问题,因为我需要创建一个模型方法,然后在我想执行验证时应用这个模型方法。

问题是,当我尝试使用“this”时,return 是“user”。

谁能给我解释一下原因和一些可能的解决方法? ty.

const { DataTypes } = require('sequelize')
const sequelize = require('../sequelize/db')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')

const User = sequelize.define('user', {
    id: {
        type: DataTypes.STRING,
        allowNull: false,
        primaryKey: true
    },
    name: {
        type: DataTypes.STRING,
        require: true,
        allowNull: false,
        unique: true,
        validate: {
            len: [4, 12]
        }
    },
    password: {
        type: DataTypes.STRING,
        require: true,
        allowNull: false,
        validate: {
            len: {
                args: [6, 12],
                msg: 'password between 6 and 12 characters'
            },
            async set(password) {
                this.setDataValue('password', await bcrypt.hash(password, 8))
            }
        }
    },
    email: {
        type: DataTypes.STRING,
        require: true,
        allowNull: false,
        unique: true,
        validate: {
            isEmail: true
        }
    },
    avatar: {
        type: DataTypes.BLOB,
    },
    profile: {
        type: DataTypes.TEXT
    }
})

User.genAuthToken = async function () {
    const user = this
    const token = jwt.sign({ _id: user.id }, 'qweasd', { expiresIn: '7 days' })
    return token
}

const a = async () => {
    await User.create({
        id: 'asdd',
        name: 'nishia',
        email: 'emaia@am.me',
        password: 'asdasd'
    })
    const token = await User.genAuthToken()
}

a()

您需要实例方法而不是 class(静态)方法:

User.prototype.genAuthToken = async function () {
    const user = this
    const token = jwt.sign({ _id: user.id }, 'qweasd', { expiresIn: '7 days' })
    return token
}
...
const a = async () => {
    const newUser = await User.create({
        id: 'asdd',
        name: 'nishia',
        email: 'emaia@am.me',
        password: 'asdasd'
    })
    const token = await newUser.genAuthToken()
}