我想用 postgres
添加一个实例方法到 Sequelize
User
模型。 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
中有模型的 Instance
但不是实例方法。在 Sequelize
模型中添加实例方法的正确方法是什么?
最佳答案
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
}
关于node.js - 如何在 Sequelize 模型中添加实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52937747/