Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript how to pass variable into init

I have a model named user.js that uses sequelize:

const { Sequelize, Model, STRING,} = require('sequelize');

var sequelizeCredentials = null;

class User extends Model{
    constructor(sequelizeCredentials){
        this.sequelizeCredentials = sequelizeCredentials;
    }
};
console.log(sequelizeCredentials);
User.init(
    {
        id: {type:Sequelize.UUID, defaultValue: Sequelize.UUIDV4, primaryKey:true},
        username: {type:STRING, allowNull:false},
        password: {type:STRING, allowNull:false},
        name: {type:STRING, allowNull:false},
    },{sequelize: sequelizeCredentials, modelName:'user'}
);
module.exports = { User };

I am trying to pass my sequelize credentials from the app.js like this:

const express = require('express');
const { Sequelize } = require('sequelize');
const mysql = require('mysql2/promise');
const user = require('./modals/user');
const app = express();

app.use(express.json());

initialize();
async function initialize() {
   const sequelize = new Sequelize(
        'express_project',
        'root',
        '',
        {
            dialect: 'mysql'
        }
    );

    localUser = new user.User(sequelize);

    await sequelize.sync();
}

However, i keep getting an error saying "No Sequelize instance passed".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am very new to JS/TS? So I appreciate your help.

>Solution :

try this

const { Sequelize, Model, STRING,} = require('sequelize');

class User extends Model{
  constructor(){
    super();
  }
  static init(sequelize) {
   return super.init({
     id: {type:Sequelize.UUID, defaultValue: Sequelize.UUIDV4, primaryKey:true},
     username: {type:STRING, allowNull:false},
     password: {type:STRING, allowNull:false},
     name: {type:STRING, allowNull:false},
    },{sequelize, modelName:'user'});
   }
}
module.exports = { User };

in app.js

async function initialize() {
  const sequelize = new Sequelize(
    'express_project',
    'root',
    '',
    {
        dialect: 'mysql'
    }
);

User.init(sequelize);

await sequelize.sync();

}

more od es6 classes with sequlize check this out https://codewithhugo.com/using-es6-classes-for-sequelize-4-models/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading