【问题标题】:How to add an instance method in Sequelize model如何在 Sequelize 模型中添加实例方法
【发布时间】:2021-03-24 05:55:46
【问题描述】:

我想用postgresSequelize 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 模型中添加实例方法的正确方法是什么?

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案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 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
    }
    

    【讨论】:

      【解决方案2】:

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

      Cannot access Sequelize instance methods

      这里有更多阅读: https://codewithhugo.com/using-es6-classes-for-sequelize-4-models/

      【讨论】:

        猜你喜欢
        • 2019-06-25
        • 2017-07-12
        • 2018-09-28
        • 2013-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-02
        相关资源
        最近更新 更多