Cannot access Sequelize instance methods

半腔热情 提交于 2019-12-12 01:49:04

问题


I get the following error when I attempt to call the generateHash instance method I've defined on my User model:

User.generateHash(...).then is not a function

Here's the model definition itself:

const User = sequelize.define('User', 
{
    firstName: {
        type: Sequelize.TEXT,
        field: 'first_name'
    },
    lastName: {
        type: Sequelize.TEXT,
        allowNull: false,
        field: 'last_name'
    },
    userName: {
        type: Sequelize.TEXT,
        field: 'user_name',
        allowNull: false
    },
    password: {
        type: Sequelize.TEXT,
        allowNull: false
    }
}, {
    tableName: 'users',
    underscored: true,
    classMethods: {
        associate: function(models) {
            User.hasMany(
      models.Trip,
                {
                    as: 'trips',
                    foreignKey: {
                        name: 'userId',
                        field: 'user_id',
                        allowNull: false
                    },
                    onDelete: 'CASCADE'
                });
        },
    },
    instanceMethods: {
        generateHash: function(password) {
            return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },
        validatePassword: function(password) {
            return bcrypt.compareSync(password, this.password);
        },
        apiRepr: function() {
            return {
                id: this.id,
                firstName: this.firstName,
                lastName: this.lastName,
                userName: this.userName
            };
        }
    }
});

Here's the endpoint where I attempt to call the method:

router.post('/', (req, res) => {
let {userName, password, firstName, lastName} = req.body;

// if no existing user, hash password
return User.generateHash(password)
    .then(hash => {
        // create new user
        return User.create({
            firstName: firstName,
            lastName: lastName,
            userName: userName,
            password: hash
        });
    })
    .then(user => {
        // send back apirRepr data
        return res.status(201).json(user.apiRepr());
    })
    // error handling
    .catch(err => {
        if (err.name === 'AuthenticationError') {
            return res.status(422).json({message: err.message});
        }
        res.status(500).json({message: 'Internal server error'});
    });});

I'm totally stuck. Any ideas?


回答1:


You are calling .then() on something that does not return a promise. Try this:

router.post('/', (req, res) => {
let {userName, password, firstName, lastName} = req.body;
let hash = User.generateHash(password);
// if no existing user, hash password
return User.create({
        firstName: firstName,
        lastName: lastName,
        userName: userName,
        password: hash
    })
    .then(user => {
        // send back apirRepr data
        return res.status(201).json(user.apiRepr());
    })
    // error handling
    .catch(err => {
        if (err.name === 'AuthenticationError') {
           return res.status(422).json({message: err.message});
        }
        return res.status(500).json({message: 'Internal server error'});
    });



回答2:


In sequelize V4 class and instance methods are removed. Now you have to make it this way:

const Model = sequelize.define('Model', {
    ...
});

// Class Method
Model.associate = function (models) {
    ...associate the models
};

// Instance Method
Model.prototype.someMethod = function () {..}

More information here Sequelize v4 breaking changes



来源:https://stackoverflow.com/questions/43954112/cannot-access-sequelize-instance-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!