如何在Sequelize模型中添加实例方法

时间:2018-10-22 21:04:48

标签: node.js sequelize.js

我想使用SequelizeUser postgres模型添加实例方法。 User模型的定义如下:

const Sql = require('sequelize');
const db = require("../startup/db");

const User = db.define('user', {
    id: {type: Sql.INTEGER,
         primaryKey:true,
         min: 1},
    name: {type: Sql.STRING,
           allowNull: false,
           min: 2,
           max: 50
        },
    email: {type: Sql.STRING,
            isEmail: true},       
    encrypted_password: {type: Sql.STRING,
                         min: 8},
    createdAt: Sql.DATE,
    updatedAt: Sql.DATE
});

我正在模型User中寻找类似的东西:

User.instanceMethods.create(someMethod => function() {
   //method code here
   });

实例方法可以这样访问:

let user = new User();
user.someMethod();

Instance中的模型有Sequelize,但实例方法中没有。在Sequelize模型中添加实例方法的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

const User = db.define('user', {
    id: {type: Sql.INTEGER,
         primaryKey:true,
         min: 1},
    name: {type: Sql.STRING,
           allowNull: false,
           min: 2,
           max: 50
        },
    email: {type: Sql.STRING,
            isEmail: true},       
    encrypted_password: {type: Sql.STRING, min: 8},
    createdAt: Sql.DATE,
    updatedAt: Sql.DATE
});


// This an hook function
User.beforeSave((user, options) => {
   // Do something
});

// This is a class method
User.classMethod = function (params) {
    // Do something with params
}

// This is an instance method
User.prototype.instanceMethod = function (params) {
    // Do something with params
}

答案 1 :(得分:0)

这是问题的答案。请参阅Mariano的回复。

Cannot access Sequelize instance methods

更多阅读内容: https://codewithhugo.com/using-es6-classes-for-sequelize-4-models/