我想使用Sequelize
向User
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
模型中添加实例方法的正确方法是什么?
答案 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/