Search code examples
javascriptsqlnode.jsormsequelize.js

Sequelize built-in function calls


I am trying to call sequelize builtin functions. I have initialized my sequelize files using the command npx sequelize-cli init My migration file for create user named 20231027060652-create-user.js in migrations folder is:

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('User', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      username: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      password: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      successfully_verified: {
        type: Sequelize.BOOLEAN,
        allowNull: false,
        defaultValue: false,
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('Users');
  }
};

My model for sequelize is as follows:

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  }
  User.init({
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      allowNull: false,
    },
    username: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    successfully_verified: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false,
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false,
    },
  }, {
    sequelize,
    modelName: 'User',
  });
  return User;
};

The index.js created by default through the command is as follows:

'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const process = require('process');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (
      file.indexOf('.') !== 0 &&
      file !== basename &&
      file.slice(-3) === '.js' &&
      file.indexOf('.test.js') === -1
    );
  })
  .forEach(file => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

I'm trying to run a simple function inside server.js where I'm trying to call any in built function of sequelize but it says that the function is not defined even though the test passes for connection. Any help would be greatly appreciated. Thankyou. Server.js file:

const express = require("express");
const app = express();
const cors = require("cors");
const PORT = process.env.PORT;
const db = require("./models");
const User = require("./models/User");

app.use(express.json());
app.use(cors());
db.sequelize.sync({force: true}).then(async (req) => {
  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });
  const newUser = {
    username: "abc",
    password: "123123",
    successfully_verified: false,
  };
  try {
    await sequelize.authenticate();
    console.log("Connection has been established successfully.");
    const user = await User.create(newUser);
    console.log(user);
  } catch (error) {
    console.error("Error creating user:", error);
  }
  return;

I would like to mention that the migrations are being successfully performed and the users table with all of the columns as mentioned in migrations are created inside the database. Exact wordings of error:

Listening on port 3500
Executing (default): SELECT 1+1 AS result
Connection has been established successfully.
TypeError: User.create is not a function

I tried to use sequelize in built methods but were not able to do so


Solution

  • The issue is because you are trying to call User.create(newUser), but you should use Sequelize's function for creating records instead. To fix this, use the create method on the User model provided by Sequelize.

    You can do this by import the User model from the db object that you exported from your models/index.js file

    const User = db.User; // Use the User model from the db object
    

    Then the below code will work as expected.

    const user = await User.create(newUser); // Use User.create
    

    If it helps, please accept the answer and upvote it :)