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

标签 node.js sequelize.js

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

相关文章:

node.js - 使用 redis 水平扩展 socket.io

javascript - Node 中数组解构的奇怪行为

Node.js 快速连接被/拒绝

javascript - 如何在nodejs中接收上传的文件

mysql - Sequelize bulkCreate : updateOnDuplicate

node.js - Req.User 值默认为 Oauth 身份验证重定向后数据库中的第一条记录

node.js - Sequelize 列 Table.createdAt 不存在

node.js - 如何运行sequelize db :migrate on Elastic Beanstalk EB with env vars? 如何访问容器命令中的.env vars?

node.js - 如何替换文件(或多个文件)中的多行?

node.js - 如何使用 sequelize 搜索经纬度的数据库表