1

I am totally a newbie to Node.js. It's my first project in node. Since I use Laravel for most of my projects I am familiar with MVC (Model View Controller). So I went through the Sequelize ORM documentation regarding Models. 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.

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. So am I doing anything wrong, or it is not possible in Sequelize? Thanks in Advance

1 Answer 1

4

The reason test function does not return anything its because findOne is async and return would happen before findOne is complete.

All you have to do is return the User.findOne() which in turn would return a promise. 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

PS: The test function here is a class method.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks man it worked but data also returned a promise so i used another then call in route file
Happy to help. You can then just return User.test = () => User.findOne(). and console.log(data) inside the then. No need for two .then
Would you clarify little bit more like how to use await and async
There are lot of articles like this and this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.