Node.js 如何在Sequelize模型中添加实例方法
我想用Node.js 如何在Sequelize模型中添加实例方法,node.js,sequelize.js,Node.js,Sequelize.js,我想用postgres为SequelizeUser模型添加一个实例方法用户模型定义如下: 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,
postgres
为Sequelize
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();
Sequelize
中的模型有实例
,但实例方法没有。在Sequelize
模型中添加实例方法的正确方法是什么 以下是问题的答案。请参见Mariano的回复
以下是更多阅读:
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 is 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
}