I have 2 express.js applications and run sequelize.sync(), but in my first app it generate the tables, and the others not generate the tables, i wonder why, because the script is identic.
database.js
const Sequelize = require('sequelize');
const sequelize = new Sequelize('student-affairs', 'root', '', {
dialect: 'mysql',
host: 'localhost',
operatorsAliases: false,
});
module.exports = sequelize;
organization.js
const Sequelize = require('sequelize');
const sequelize = require('../configs/database');
const Organization = sequelize.define('organization', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING,
allowNull: false
},
logo: {
type: Sequelize.STRING
},
createdBy: {
type: Sequelize.INTEGER,
allowNull: false
},
updatedBy: {
type: Sequelize.INTEGER,
allowNull: false
}
});
module.exports = Organization;
app.js
// Database
const sequelize = require('./configs/database');
sequelize
.sync()
.then(result => {
console.log(result);
app.listen(3001);
})
.catch(err => {
console.log(err);
});
But after i log it, it always return the models empty like this
models: {},
modelManager: ModelManager { models: [], sequelize: [Circular] },
it doesn't have the models. anyone can explain why? thanks
I just realize that i am not call the organization model in app.js, once i define it in app.js and it fix the problem.
I think it's a basic mistake. Now i understand how it works.
// Models
const Organization = require('./models/organization');
sequelize
.sync()
.then(result => {
app.listen(3000);
})
.catch(err => {
console.log(err);
});
Related
I am very new with backend and database
I am using node ,sequelize and mysql2 to connect to connect to my_db that I have created it through MySQl workbench .
this is my code
server.js
const express = require("express");
const app = express();
const sequelize = require("./utils/db");
sequelize.sync().then((res) => {
console.log(res);
app.listen(5000, () => {
console.log("runned");
});
}).catch(err=>{
console.log(err);
})
utils/db.js
const { Sequelize } = require("sequelize");
const sequelize = new Sequelize("my_db", "root", "3132820", {
dialect: "mysql",
host: "localhost",
});
module.exports = sequelize;
models/toto.js
const { DataTypes } = require("sequelize");
const sequelize = require("../utils/database");
const Todo = sequelize.define("Todo", {
//? Model attributes
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
text: {
type: DataTypes.STRING,
allowNull: false,
},
completed: {
type: DataTypes.BOOLEAN,
defaultValue: false,
allowNull: true, //? default is true,
},
});
module.exports = Todo;
and I get this error
and also I have created database in mysql
how can I fix this ?
In the last pic, it's not a database, it's just a connection to your mysql server, you need to create a database in your mysql server.
I've been trying to create associations with Sequelize but to no avail, I kept getting a hasOne is not a function error. I've learned that it may be because of circular dependencies with my imports. So I started using the Sequelize instance in my index.js file and importing that instance in other model files:
index.js:
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};
const practAppt = require('./practAppt')
const practUser = require('./practUsers')
practAppt.hasOne(practUser, {foreignKey: "email"})
practUser.hasMany(practAppt, {foreignKey: "client"})
var sequelize = new Sequelize({
dialect: 'sqlite',
storage: 'C:/backend/db.sqlite3'
});
//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');
})
.forEach(file => {
console.log("FILE", file)
const model = require((path.join(__dirname, file)));
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
practUsers.js
const Sequelize = require('sequelize')
const Op = Sequelize.Op
const db = require("./index")
const practUser = db.define("practUsers", {
// attributes
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING,
allowNull: false
},
address: {
type: Sequelize.STRING,
allowNull: false
},
unit: {
type: Sequelize.STRING,
allowNull: false
},
city: {
type: Sequelize.STRING,
allowNull: false
},
province: {
type: Sequelize.STRING,
allowNull: false
},
postal_code: {
type: Sequelize.STRING,
allowNull: false
},
phoneNumber: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
allowNull: false,
unique: true
},
birthdate: {
type: Sequelize.STRING,
allowNull: false
},
healthCardNumber: {
type: Sequelize.STRING,
allowNull: false,
unique: true
},
profession: {
type: Sequelize.STRING,
allowNull: false
},
designation: {
type: Sequelize.STRING,
allowNull: false
},
userType: {
type: Sequelize.STRING,
allowNull: false
},
})
// automatically create the table with the model definition
//sequelize.sync()
// test the connections
module.exports = {practUser}
But now it's telling me db.define is not a function, even if I export sequelize in index.js I get the same error. How do I properly create associations? I should create them in index.js correct? Or does it not matter? The docs seems to be useless on this front.
your db object as exported from index.js doesn't have the define method. You probably need to write:
const practUser = db.sequelize.define(....
I have connected my app to an existing database. The database table currently has 3 entries but, when I query the model using findAll only an empty array is returned. Im not sure if this has something to do with the database already and existing and connecting to it through models. I am also syncing all files in the index file in the models directory.
//Courses Model for sequelize
const Sequelize = require('sequelize');
module.exports = (sequelize) => {
class Courses extends Sequelize.Model{}
Courses.init({
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
title: {
type: Sequelize.STRING,
allowNull: false
},
description: {
type: Sequelize.TEXT,
allowNull: false
},
estimatedTime: {
type: Sequelize.STRING,
},
materialsNeeded: {
type: Sequelize.STRING,
},
createdAt: {
type: Sequelize.DATE,
allowNull: false
},
updatedAt: {
type: Sequelize.DATE,
allowNull: false
},
userId: {
type: Sequelize.INTEGER,
references: { model: 'users', key: 'id' },
onDelete: 'CASCADE',
allowNull: false
}
}, {sequelize, modelName: 'courses'});
Courses.associate = (models) => {
models.courses.belongsTo(models.users, {foreignKey: "userId"});
};
return Courses
}
// Router with findAll query
const router = require('express').Router();
const db = require('../models/');
router.get('/', async(req, res) => {
try {
console.log(await db.courses.findAll());
} catch(err) {
console.error(err);
}
res.json({msg: "None"})
});
module.exports = router;
[This is the courses table currently][1]
[1]: https://i.stack.imgur.com/2KkK6.png
This is javascript level issuse I guess. You can't use await statement like that. Please try this out first.
onst router = require('express').Router();
const db = require('../models/');
router.get('/', async (req, res) => {
try {
const courese = await db.courses.findAll()
console.log(courses)
res.send({ courses })
} catch(err) {
console.error(err);
}
res.json({msg: "None"})
});
module.exports = router;
If the problem remains after running this, check if your config is pointing right database.
For checking whether this is problem.
Change your config to point existing database
Run the code
Change your config to point local database with different schema
Do the sequelize sync
Run the code
By doing so, you can check what is the real problem in your code.
I am new to nodejs and Sequelize and have been having an issue that I cannot figure out how to get over. I want to use a connection I created and exported it to a module.
Like this:
const dotEnv = require('dotenv');
const Sequelize = require('sequelize');
dotEnv.config();
module.exports.connection = async () => {
try{
const sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASSWORD, {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
dialect: 'mysql',
logging: false,
define: {
charset: 'utf8',
collate: 'utf8_general_ci',
},
});
await sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(error => {
throw error;
});
}catch(error){
throw error;
}
}
I then have another file where I want to use it that looks like this
const Sequelize = require('sequelize');
const { connection }= require('../database');
const accountModel = connection.define('accounts', {
// attributes
id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
primaryKey: true
},
name: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
unique: true
},
password: {
type: Sequelize.STRING,
allowNull: false,
//is: /^[0-9a-f]{64}$/i
},
permission: {
type: Sequelize.STRING,
allowNull: false
},
discount: {
type: Sequelize.INTEGER,
allowNull: false
}
}, {
freezeTableName: true
});
module.exports = connection.model('accounts', accountModel);
The problem is that I get told that: TypeError: connection.define is not a function,
The connection works, the database is running, everything else works
And last if I do it like this, it works too:
const dotEnv = require('dotenv');
const Sequelize = require('sequelize');
dotEnv.config();
const sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASSWORD, {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
dialect: 'mysql',
logging: false,
define: {
charset: 'utf8',
collate: 'utf8_general_ci',
},
});
const accountModel = sequelize.define('accounts', {
// attributes
id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
primaryKey: true
},
name: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
unique: true
},
password: {
type: Sequelize.STRING,
allowNull: false,
//is: /^[0-9a-f]{64}$/i
},
permission: {
type: Sequelize.STRING,
allowNull: false
},
discount: {
type: Sequelize.INTEGER,
allowNull: false
}
}, {
freezeTableName: true
});
module.exports = sequelize.model('accounts', accountModel);
I am really not sure why the module one does not work but the direct method does. I have tried to search Google and Stack Overflow for a solution.
The problem in your first approach is that you exported first of all an async function and not the Sequelize instance (as it is in your second example) and secondly the function itself is not returning anything. That's why there is no connection.define() function when you require that in another file.
try this in database.js and it should work:
module.exports.connection = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASSWORD, {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
dialect: 'mysql',
logging: false,
define: {
charset: 'utf8',
collate: 'utf8_general_ci',
},
});
You can do all that authenticate() and try {} catch (error) {} somewhere else for example in your very first js file where you starting the server by requiring the same database.js file. But for the model definitions it's important that you are exporting just the new Sequelize() instance to them to be able to use define()
I would do something like this. In the connections file you export the function then in the accountModel file you import and invoke the function.
connection.js:
exports.connection= async function() { // Stuff here }
accountModel.js:
const { connection }= require('../database');
let connection = await connection.connection();
i'm using NodeJS & Sequelize for a school project and i'm struggling on making associations w/ sequelize work. I tried a couple of things before but nothing that made my day.
Basically the thing is that a user can have several playlists (hasMany).
And a playlist belongs to a user (belongsTo).
My error is:
Association with alias "playlist" does not exist on users
Here are my models:
/* USER MODEL */
const Sequelize = require('sequelize');
const { db } = require('../utils/db');
const User = db.define('users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
userID: {
type: Sequelize.INTEGER,
allowNull: false,
field: 'user_id',
},
firstName: {
type: Sequelize.STRING,
field: 'first_name',
allowNull: false,
},
}, {
underscored: true,
tableName: 'users',
freezeTableName: true, // Model tableName will be the same as the model name
});
module.exports = {
User,
};
/* PLAYLIST MODEL */
const sequelize = require('sequelize');
const { db } = require('../utils/db');
const Playlist = db.define('playlist', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: sequelize.INTEGER,
},
name: {
type: sequelize.STRING,
field: 'name',
allowNull: false,
},
coverUrl: {
type: sequelize.STRING,
field: 'cover_url',
allowNull: true,
},
ownerId: {
type: sequelize.INTEGER,
allowNull: false,
references: {
model: 'users',
key: 'user_id',
},
},
}, {
underscored: true,
tableName: 'playlist',
freezeTableName: true,
});
module.exports = {
Playlist,
};
Here is how i load my models:
const { Credentials } = require('./credentials');
const { User } = require('./users');
const { Playlist } = require('./playlist');
function loadModels() {
User.associate = (models) => {
User.hasMany(models.Playlist, { as: 'playlist' });
};
Playlist.associate = (models) => {
Playlist.belongsTo(models.User, { foreignKey: 'owner_id', as: 'owner' });
};
Credentials.sync({ force: false });
User.sync({ force: false });
Playlist.sync({ force: false });
}
module.exports = {
loadModels,
};
And finally here is my query where i get this error:
const express = require('express');
const { auth } = require('../../middlewares/auth');
const { Playlist } = require('../../models/playlist');
const { User } = require('../../models/users');
const router = express.Router();
router.get('/playlist', [], auth, (req, res) => {
User.findOne({
where: { userID: req.user.user_id }, include: 'playlist',
}).then((r) => {
console.log(r);
});
});
module.exports = router;
I'm trying to get all the playlist that belongs to a user.
I removed all the useless code (jwt check etc..)
So when i'm doing a get request on /playlist I get:
Unhandled rejection Error: Association with alias "playlist" does not exist on users.
I understand the error but don't understand why i get this.
What did I miss, any ideas ?
Thanks,
I finally fixed it by re-make all my models and definitions with migrations.
I had the same problem and the solution was that Sequelize pluralize the models name so in my case "playlist" does not exist on users because Sequelize pluralized my model so I had to put "Playlists" instead.