简体   繁体   English

如何在Sequelize中在导入的模型中创建自定义方法或函数

[英]How to create custom methods or functions inside imported models in Sequelize

I am totally a newbie to Node.js . 我完全是Node.js的新手。 It's my first project in node. 这是我在node中的第一个项目。 Since I use Laravel for most of my projects I am familiar with MVC (Model View Controller). 由于我在大多数项目中使用Laravel,所以我对MVC(模型视图控制器)很熟悉。 So I went through the Sequelize ORM documentation regarding Models. 因此,我浏览了有关模型的Sequelize ORM文档。 I learned how to import one model per file and it worked but when I added custom functions to the User model, the function works fine but doesn't return anything. 我学习了如何为每个文件导入一个model ,并且该model可以工作,但是当我向User模型添加自定义函数时 ,该函数可以正常工作,但不返回任何内容。

Here's my DB File 这是我的数据库文件

const fs = require('fs');
var Sequelize = require('sequelize');
var sequelize = new Sequelize('database_name', 'userName', 'password', {
  host: 'localhost',
  dialect: 'mysql',
  operatorsAliases: false,
  logging:false,

  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  },

  // SQLite only
  //storage: 'path/to/database.sqlite'
});



sequelize.import('./../models/User.js');
var db=sequelize.models;



   module.exports={db,connectionCheck};

and here's User Model' Code 这是用户模型的代码

module.exports = (sequelize, DataTypes) => {
  var User = sequelize.define('User', {},{
         timestamps: false,
        freezeTableName:true,
        tableName:'agent_info'
      });
/*This is the custom function that I added*/
      User.test = function(){
         User.findOne().then(data =>{
           console.log(data);
           return data;
        });
      };


  return User;
};

and finally Route file's code 最后是路由文件的代码

 app.get('/',(req,res,next) =>{
      var temp=db.User.test();
      console.log(temp);
    });

Here I am invoking user.test() function (Custom Model Function ) the function seems to work as expected, but isn't returning anything. 在这里,我正在调用user.test()函数(自定义模型函数),该函数似乎按预期运行,但未返回任何内容。 So am I doing anything wrong, or it is not possible in Sequelize? 所以我做错什么了吗,还是在Sequelize中不可能? Thanks in Advance 提前致谢

The reason test function does not return anything its because findOne is async and return would happen before findOne is complete. 原因test函数不返回任何内容,因为findOne是异步的,并且返回将在findOne完成之前发生。

All you have to do is return the User.findOne() which in turn would return a promise. 您所需要做的就是返回User.findOne() ,而User.findOne()会返回一个User.findOne() Something like this 像这样

User.test = () => User.findOne().then((data) => {
    console.log(data);
    return data;
  });

Now you can use User.test().then((result) => { .. } if you are using promises or const result = await User.test(); if you want to use async/await 现在,如果您使用promisesconst result = await User.test();则可以使用User.test().then((result) => { .. } const result = await User.test();如果要使用async/await const result = await User.test();则可以使用const result = await User.test();

PS: The test function here is a class method . PS:这里的test功能是一个class method

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM