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".
I am very new to JS/TS? So I appreciate your help.
CodePudding user response:
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/