Sequelize with sqlite3 doesn't create a database - node.js

Could you please help me to solve the problem?
I use sqlite3 with sequelize npm package. After running migrations I don't see errors in console but I also don't see any database file. Also I can run migrations again and again, it doesn't look like correct behavior.
Here is my /config/config.js file:
const path = require('path');
module.exports = {
test: {
username: 'root',
password: 'root',
database: path.join(__dirname, '..', 'database_test.sqlite'),
host: 'localhost',
dialect: 'sqlite',
logging: console.log,
operatorsAliases: false
}
};
Here is migrations/XXXXXXXXXXXXXX-create-appeal.js file:
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => queryInterface.createTable('appeals', {
appealId: {
allowNull: false,
primaryKey: true,
type: Sequelize.UUID
},
name: {
allowNull: false,
type: Sequelize.STRING
},
description: {
type: Sequelize.STRING(511)
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
}),
down: queryInterface => queryInterface.dropTable('appeals')
};
Here is models/index.js file
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(path.join(__dirname, '..', 'config', 'config.js'))[env];
const db = {};
let sequelize = new Sequelize(config.database, config.username, config.password, config);
fs
.readdirSync(__dirname)
.filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'))
.forEach(file => {
const model = sequelize.import(path.join(__dirname, file));
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;
Here is models/appeal.js file:
'use strict';
module.exports = (sequelize, DataTypes) => {
const Appeal = sequelize.define('appeals', {
appealId: {
allowNull: false,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
type: DataTypes.UUID,
validate: {
isUUID: 4
},
get() {
return this.getDataValue('appealId').toLowerCase();
}
},
name: {
type: DataTypes.STRING,
allowNull: false
},
description: {
type: DataTypes.STRING(511)
}
}, {
tableName: 'appeals'
});
Appeal.associate = models => {
// associations can be defined here
};
return Appeal;
};
Another strange thing: if I put console log or error throwing in models/index.js, I'll see nothing, so that nodejs doesn't execute file.
Thanks.

I found a reason: it should be storage instead of database in config:
const path = require('path');
module.exports = {
test: {
username: 'root',
password: 'root',
storage: path.join(__dirname, '..', 'database_test.sqlite'),
host: 'localhost',
dialect: 'sqlite',
logging: console.log
}
};

Try it:
./config.js
const path = require('path');
module.exports = {
development: {
username: 'root',
password: 'root',
database: path.join(__dirname, '..', 'database_test.sqlite'),
host: 'localhost',
dialect: 'sqlite',
logging: true,
operatorsAliases: false
}
};
.sequelizerc
const path = require('path');
module.exports = {
'models-path': path.resolve('./models'),
'seeders-path': path.resolve('./seeders'),
'migrations-path': path.resolve('./migrations'),
'config': path.resolve('./config', 'config.js')
};

Related

Error("No Sequelize instance passed") No Sequelize instance passed

Hello can somebody help me with this ? I was doing my controllers and I can access to my model like this "const { User } = require("../models/User");" but than when I send my request I had this message "TypeError: Cannot read property 'create' of undefined" so something was missing.
So I change my call model to this "const { User } = require("../models");".
And I went on my model index.js (so connection sequelize) and I add fs function and Objectif.key. After all those changes I have the error "No Sequelize instance passed".
So maybe somebody can help with this because I don't see the problem
So this is my model index.js
//sequelize importe
const fs = require("fs");
const path = require("path");
const Sequelize = require("sequelize");
const db = {};
const basename = path.basename(__filename);
let sequelize = new Sequelize("groupomania", "root", "root", {
host: "localhost",
dialect: "mysql",
});
sequelize
.authenticate()
.then(() => {
console.log("Connection has been established successfully!");
})
.catch((err) => {
console.log("Can't establish database connection:\n" + err);
});
fs.readdirSync(__dirname)
.filter((file) => {
console.log( file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js");
return (
file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
);
})
.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;
This is my model User.js
const { Model } = require("sequelize");
module.exports = (Sequelize, DataTypes) => {
class User extends Model {
toJSON() {
return {
...this.get(),
password: undefined,
};
}
}
User.init(
{
id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4 },
nom: { type: DataTypes.STRING, allowNull: false },
prenom: { type: DataTypes.STRING, allowNull: false },
email: {
type: DataTypes.STRING,
allowNull: false,
validate: { notNull: true, notEmpty: true, isEmail: true },
},
status: { type: DataTypes.STRING, allowNull: false },
password: { type: DataTypes.STRING, required: true },
},
{ Sequelize, tableName: "users", modelName: "User" }
);
return User;
};
My controllers/user.js
/*const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");*/
const { User } = require("../models/User");
module.exports.signup = async (req, res) => {
try {
const user = await User.create({
nom: "Jp",
prenom: "remy",
email: "remy#gmail.fr",
password: "motdepasse",
});
res.status(200);
throw Error("erreur est survenu");
} catch (erreur) {
console.log(erreur);
res.status(200).json({ erreur });
}
};
My route user
const express = require("express");
const router = express.Router();
const userCtrl = require("../controllers/user");
router.post("/signup", userCtrl.signup);
/*router.post("/login", userCtrl.login);*/
module.exports = router;
Thank you for any help! :)
The answer was that on my model user the "S" of sequelize must have an s minus

Unable to develop assosciations between models in sequelize

I am creating realtionship (one to many) between User model and Task model
I have crated the reference column in the migration too
I am using sequlize ORM with sequelize cli. Everything works fine when I try alternative method that i will explain later but If i try to do it according the documentation it gives me error
Task is not associated to User
WORKING ALTERNATIVE METHOD
IN end of index.js file I created relations and it works as expected
db.user = require("../models/user.js")(sequelize, Sequelize);
db.tasks = require("../models/Task.js")(sequelize, Sequelize);
db.user.hasMany(db.tasks, { as: "user_tasks",foreignKey: "userId" });
db.tasks.belongsTo(db.user, {
foreignKey: "userId",
as: "task_user",
});
but when i follow the documetation i got error that i mentioned earlier
According to document
Model User.js
module.exports = (sequelize, DataTypes) => {
const User =sequelize.define('User',{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
age: {
type: DataTypes.INTEGER,
},
email: {
type: DataTypes.STRING,
},
createdAt: {
allowNull: false,
type: DataTypes.DATE
},
updatedAt: {
allowNull: false,
type: DataTypes.DATE
}
});
User.associate = (models) =>{
User.hasMany(models.Tasks, {
as: 'user_tasks',
foreignKey: 'userId'}
);
};
return User;
};
Model: Task.js
module.exports = (sequelize, DataTypes) => {
const Task = sequelize.define('Task', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
title: {
type: DataTypes.STRING,
allowNull: false,
},
userId: {
type: DataTypes.INTEGER,
},
});
Task.associate = function(models) {
Task.belongsTo(models.User, {
as:'owner',
foreignKey:'userId',
onDelete: "cascade"
});
};
return Task;
}
This is how i am trying to get data from database
controller
const User = db.user
const {Tasks} = db.tasks
exports.usertasks = async(req,res)=>{
// const users = await User(db.sequelize,db.Sequelize).findAll({
const users = await User.findAll({
include:[{model:Tasks,as:"user_tasks"}]
});
res.json(users)
console.log("All users with their associated tasks:", JSON.stringify(users, null, 4));
}
My Index.js file
'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 = {};
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 => {
const model = require(path.join(__dirname+'../models/', file))(sequelize, Sequelize.DataTypes);
console.log(model);
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
//relations THIS IS WORKING AND I AM JUST CURIOUS WHETHER TO USE THIS APPROACH OR NOT
// db.user = require("../models/user.js")(sequelize, Sequelize);
// db.tasks = require("../models/Task.js")(sequelize, Sequelize);
// db.user.hasMany(db.tasks, { as: "user_tasks",foreignKey: "userId" });
// db.tasks.belongsTo(db.user, {
// foreignKey: "userId",
// as: "task_user",
// });
module.exports = db;
I am also attaching the picture of successful response that I get with the alternative method.
Kindly, guide whether the alternative method that I used is acceptable or should I stick to the documenation one?
.associate is not a native Model's method, so you need to call it manually.
I think in your index.js you want to do something like:
'use strict';
const Sequelize = require('sequelize');
const config = require('../config/config.json')[process.env.NODE_ENV || 'development'];
const requireAll = require('require-all');
const sequelize = config.use_env_variable
? new Sequelize(process.env[config.use_env_variable], config)
: new Sequelize(config.database, config.username, config.password, config);
const db = { sequelize };
const modelsInitializers = Object.values(requireAll({
dirname: __dirname,
recursive: false,
filter: (name) => name !== 'index.js' && name,
}));
const models = modelsInitializers.map((initializer) => {
const model = initializer(sequelize, Sequelize.DataTypes);
db[model.name] = model;
return model;
});
models.forEach((model) => {
if (model.associate) model.associate(db);
})
models.forEach((model) => {
if (model.associate) model.associate(models);
db[model.name] = model;
})
Object.entries().forEach(([modelName, model]) => {
model.associate(models);
db[modelName] = model;
});
module.exports = db;

Why sequelize is not creating all columns in the table for postgresql

I am creating a database module for my blog. I am using nodejs and sequelize module for this. The database I am using is Postgresql.
This is the sequelize initialization.
'use strict'
const Sequelize = require('sequelize')
// Creating a singletone
let sequelize = null
module.exports = function setupDatabase (config) {
if (!sequelize) {
sequelize = new Sequelize(config)
}
return sequelize
}
The singleton is to evaluate if a previus instance of sequelize was already created.
And then I have an script configuration:
'use strict'
const debug = require('debug')('diesanromero:db:setup')
const inquirer = require('inquirer')
const chalk = require('chalk')
const db = require('./')
const prompt = inquirer.createPromptModule()
async function setup () {
const answer = await prompt([
{
type: 'confirm',
name: 'setup',
message: 'This will destroy your database, are you sure?'
}
])
if (!answer.setup) {
return console.log('Nothing happend :)')
}
const config = {
database: process.env.DB_NAME || 'blog',
username: process.env.DB_USER || 'user',
password: process.env.DB_PASS || 'password',
host: process.env.DB_HOST || 'localhost',
dialect: 'postgres',
logging: s => debug(s),
setup: true
}
await db(config).catch(handleFatalError)
console.log('Success!')
process.exit(0)
}
function handleFatalError (err) {
console.error(`${chalk.red('[Fatal Error]')} ${err.message}`)
console.error(err.stack)
process.exit(1)
}
setup()
That is the script that creates the database, using the previous configuration.
Apparently all of this works fine. The database connects successfully. Then I have three models.
article.js
'use strict'
const Sequelize = require('sequelize')
const setupDatabase = require('../lib/db')
module.exports = function setupArticleModel (config) {
const sequelize = setupDatabase(config)
const stringRequired = {
type: Sequelize.STRING,
allowNull: false
}
const numberDefault = {
type: Sequelize.INTEGER,
allowNull: false,
default: 0
}
return sequelize.define('article', {
title: stringRequired,
slug: stringRequired,
description: stringRequired,
content: stringRequired,
likes: numberDefault,
shares: numberDefault
})
}
user.js
'use strict'
const Sequelize = require('sequelize')
const setupDatabase = require('../lib/db')
module.exports = function setupAuthModel (config) {
const sequelize = setupDatabase(config)
const stringRequired = {
type: Sequelize.STRING,
allowNull: false
}
return sequelize.define('user', {
name: stringRequired,
username: stringRequired,
email: stringRequired
})
}
auth.js
'use strict'
const Sequelize = require('sequelize')
const setupDatabase = require('../lib/db')
module.exports = function setupUserModel (config) {
const sequelize = setupDatabase(config)
const stringRequired = {
type: Sequelize.STRING,
allowNull: false
}
return sequelize.define('auth', {
salt: stringRequired,
hash: stringRequired,
email: {
type: Sequelize.INTEGER,
allowNull: false
}
})
}
And then my main file index.js
'use strict'
const defaults = require('defaults')
const setupDatabase = require('./lib/db')
const setupUserModel = require('./models/user')
const setupArticleModel = require('./models/article')
module.exports = async function (config) {
config = defaults(config, {
dialect: 'sqlite',
pool: {
max: 10,
min: 0,
idle: 10000
},
query: {
raw: true
}
})
const sequelize = setupDatabase(config)
const UserModel = setupUserModel(config)
const AuthModel = setupAuthModel(config)
const ArticleModel = setupArticleModel(config)
UserModel.hasMany(ArticleModel)
UserModel.hasOne(AuthModel)
ArticleModel.belongsTo(UserModel)
AuthModel.belongsTo(UserModel)
await sequelize.authenticate()
if (config.setup) {
await sequelize.sync({ force: true })
}
const User = {}
const Auth = {}
const Article = {}
return {
User,
Auth,
Article
}
}
This main file connects with sequelize.authentication successfully, and then performs migrations. Note that the User model has a 1 to 1 relationship with the Authentication model. Then the User model has a 1 to many relationship with the Article model.
It happens that the ORM does not create all the columns in the respective tables. Some if created, others not.

Sequelize sync() doesn't create all of the table models

I'm quite new to using sequelize and node.js.
I'm trying to create two tables under models 'user' and 'post' using sequelize, postgres and node.js. The problem is, that only the 'posts' table is being created while the 'users' isn't created at all.
this is the code for 4 of the files: 'models/post' , 'models/user', 'app.js' and 'utils/database' :
'models/post':
const Sequelize = require('sequelize');
const sequelize = require('../util/database');
const Post = sequelize.define('post',{
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
title:{
type: Sequelize.STRING,
allowNull: false,
},
content:{
type: Sequelize.STRING,
allowNull: false,
},
tags:{
type: Sequelize.ARRAY(Sequelize.STRING),
allowNull: false,
}
});
Post.associate = (models) => {
Post.belongsTo(models.User, {
constraints: true,
onDelete: 'CASCADE'
});
}
module.exports = Post;
'models/user':
const sequelize = require('../util/database');
const User = sequelize.define('user', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
userName: {
type: Sequelize.STRING,
allowNull: false,
},
firstName: {
type: Sequelize.STRING,
allowNull: false,
},
lastName: {
type: Sequelize.STRING,
allowNull: false,
},
bio: {
type: Sequelize.STRING,
allowNull: false,
},
password: {
type: Sequelize.STRING,
allowNull: false,
}
})
User.associate = (models) => {
User.hasMany(models.Post);
}
module.exports = User;
'app.js':
const express = require('express');
const bodyParser = require('body-parser');
const graphqlHttp = require('express-graphql');
const sequelize = require('./util/database');
const graphqlSchema = require('./graphql/schema');
const graphqlResolver = require('./graphql/resolvers');
app = express();
app.use(bodyParser.json());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Methods',
'OPTIONS, GET, POST, PUT, PATCH, DELETE'
);
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});
app.use('/graphql', graphqlHttp({
schema: graphqlSchema,
rootValue: graphqlResolver,
graphiql: true,
formatError(err) {
if (!err.originalError) {
return err;
}
const data = err.originalError.data;
const message = err.message || 'An error occurred.';
const code = err.originalError.code || 500;
return { message: message, status: code, data: data };
}
})
);
app.use((error, req, res, next) => {
const status = error.statusCode || 500;
const message = error.message;
const data = error.data;
res.status(status).json({ message: message, data: data });
});
sequelize.sync({force: true})
.then(result => {
app.listen(8080);
})
.catch(err => {
console.log(err);
});
'utils/database':
const Sequelize = require('sequelize').Sequelize;
const sequelize = new Sequelize('projectname','postgres','password',{
host: 'localhost',
dialect: 'postgres',
});
module.exports = sequelize;
(projectname and password are of-course replaced with the true values)
Register your models and their associations in utils/database
Move sync call before registering any routes
utils/database
const sequelize = new Sequelize('projectname','postgres','password',{
host: 'localhost',
dialect: 'postgres',
});
const db = {}
const models = path.join(__dirname, 'models') // path to a models' folder
fs.readdirSync(models)
.filter(function (file) {
return (file.indexOf('.') !== 0) && (file.slice(-3) === '.js')
})
.forEach(function (file) {
var model = sequelize['import'](path.join(models, file))
db[model.name] = model
})
Object.keys(db).forEach(function (modelName) {
if (db[modelName].associate) {
db[modelName].associate(db)
}
})
module.exports = sequelize

TypeError: Cannot read property 'define' of undefined

i try to change my Db from mongodb to mysql, i use sequelize instead of mongoose, and i got this error, i created the User.js model with sequelize format, but something wrong and i don't know why
const User = sequelize.define('users', {
^
TypeError: Cannot read property 'define' of undefined"
Here is my code:
server.js
const Sequelize = require('sequelize');
// DB Config
const db = require('./config/keys');
// Connect to MySql
const sequelize = new Sequelize(db.database, db.user, db.password, {
host: db.host,
dialect: 'mysql',
port: db.port
});
// Test the connection
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
const serverDB = {};
serverDB.sequelize = sequelize;
serverDB.Sequelize = Sequelize;
module.exports = serverDB;
Users.js
const serverDB = require('../server');
const sequelize = serverDB.sequelize;
const Sequelize = serverDB.Sequelize;
const User = sequelize.define('users', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
allowNull: false
},
password: {
type: Sequelize.STRING,
allowNull: false
},
avatar: {
type: STRING
},
date: {
type: Sequelize.DATE,
defaudefaultValue: Sequelize.NOW
}
});
sequelize.models.modelName
// sequelize.sync()
// .then(() => {
// console.log('User db and user table have been created')
// });
module.exports = User;
You should add
const Sequelize = require('sequelize');
in your client too.
And only export and use the lowercase sequelize.
And ensure relative path of server.js is good.

Resources