Dev1ce
Dev1ce

Reputation: 5944

How to use sequelize to fetch object data?

I am trying to implement Sequelize as an ORM in NodeJs and I am using it for Mysql,
I have 3 tables in the sample -

1. Role
2. User (Has a role)
3. Code (IsCreated by a user)

I'm unable to query the tables/models properly,
As I should be receiving an model representation of a table, which is referred as a foreign key.

Following is my DB structure -
1. Role table -
enter image description here

2. User table -
enter image description here

3. Code table -
enter image description here

Following are the table creation queries -
1. Role - CREATE TABLE role ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(100) NOT NULL, PRIMARY KEY (id) );

2. User -

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `role` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `role` (`role`),
  CONSTRAINT `user_ibfk_1` FOREIGN KEY (`role`) REFERENCES `role` (`id`)
);

3. Code -

CREATE TABLE `code` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `createdBy` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `createdBy` (`createdBy`),
  CONSTRAINT `code_ibfk_1` FOREIGN KEY (`createdBy`) REFERENCES `user` (`id`)
);

Following is my app.js file -

 const db = require('./db');
const Code = require('./code');
const User = require('./user');
const Role = require('./role');
const async = require('async');


async.waterfall([
    function(callback) {
        db
        .authenticate()
        .then(() => {
            console.log('Connection has been established successfully.');
            callback(null,"ok");
        })
        .catch(err => {
            return callback(err,null);
        });        
    },
    function(resp,callback) {
        Code.findAll({include: [{ model: User}]})
        .then(code => {
            console.log("All users:", JSON.stringify(code, null, 4));
            callback(null,"ok");
        })
        .catch(err => {
            callback(err,null);
        });

        // Code.findOne({
        //     where: {
        //         id: 1
        //     }
        // })
        // .then(code => {
        //     console.log("All users:", JSON.stringify(code, null, 4));
        // })
        // .catch(err => console.log("Error => \n",err));

    },
],
function(err, resp) {
    if (err) {
        console.log(err);
    } else {
        console.log(resp);
    }
});

Following is my db.js file -

const Sequelize = require('sequelize');

module.exports =  new Sequelize('junit', 'root', 'root', {
    host: 'localhost',
    /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
    dialect: 'mysql',
    //operatorsAliases: false,
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000
    }
  });

Following is my role.js file -

const Sequelize = require('sequelize');
const db = require('./db');
const User = require('./user');

const Role = db.define('role', {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        allowNull:false,
        autoIncrement: true
    },
    name: {
      type: Sequelize.STRING
    }
  }, {
    tableName: 'role',
    freezeTableName: true,
    timestamps: false
});

associate : (models) => {
    Role.hasMany(models.User,{
        foreignKey: 'role'
    });
};

module.exports = Role;

Following is my user.js file -

const Sequelize = require('sequelize');
const db = require('./db');
const Code = require('./code');
const Role = require('./role');

const User = db.define('user', {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        allowNull:false,
        autoIncrement: true
    },
    name: {
      type: Sequelize.STRING
    },
    email: {
        type: Sequelize.STRING
    },
    role: {
        type: Sequelize.INTEGER,
        references: {
          // This is a reference to another model
          model: Role,

          // This is the column name of the referenced model
          key: 'id'
        }
      }
  }, {
    tableName: 'user',
    freezeTableName: true,
    timestamps: false
});

associate : (models) => {
    User.hasMany(models.Code,{
        foreignKey: 'createdBy'
    });

    User.belongsTo(models.Role,{
        foreignKey: 'role'
    });
};

module.exports = User;

Following is my code.js file -

const Sequelize = require('sequelize');
const db = require('./db');
const User = require('./user');
//one-to-many
const Code = db.define('code', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    allowNull:false,
    autoIncrement: true
  },
  name: {
    type: Sequelize.STRING
  },
  // createdBy: {
  //   type: Sequelize.INTEGER
  // },
  createdBy: {
    type: Sequelize.INTEGER,
    references: {
      // This is a reference to another model
      model: User,

      // This is the column name of the referenced model
      key: 'id'
    }
  }
}, {
  tableName: 'code',
  freezeTableName: true,
  timestamps: false
});

associate : (models) => {
  Code.belongsTo(models.User,{
      foreignKey: 'createdBy'
  });
};

module.exports = Code;

When I run the app.js file I can't see the model reference of User,
But I get the usual Integer value, Can someone please help on how to properly use the Model here?

Error trace - enter image description here

Upvotes: 0

Views: 3254

Answers (1)

Eugene Shilin
Eugene Shilin

Reputation: 461

Looks like you're trying to fetch Code when connection wasn't established yet.

Try this:

const db = require('./db');
const Code = require('./code');
const User = require('./user');
const Role = require('./role');

function run() {
   return db
       .authenticate()
       .then(() => Code.findOne({ // you can try execute whenever query you want here 
          where: {
            id: 1
          }})
          .then(code => {
            console.log("All users:", JSON.stringify(code, null, 4));
          })
          .catch(err => console.log("Error => \n",err)))
        .catch(err => {
          console.error('Unable to connect to the database:', err);
        });
} 

run();

Upvotes: 1

Related Questions