gpt4 book ai didi

node.js - 如何在 Sequelize 模型中添加实例方法

转载 作者:搜寻专家 更新时间:2023-11-01 00:50:16 24 4
gpt4 key购买 nike

我想用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com