I can't create another table with postgresql and node.js - node.js

const Sequelize = require("sequelize");
const db = require("../db");
const user = require("../models/userModel");
const employees = db.define("employees", {
firstname: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
},
lastname: {
type: Sequelize.STRING,
allowNull: false,
},
userId: {
type: Sequelize.INTEGER,
references: {
model: user,
key: "id",
},
},
});
employees.sync({ alter: true });
module.exports = employees;
Okay,so I have two tables already created, in my terminal they appear with create table if not exists but not for this table,but not for this table,I missed something? pg version :8.7.1
const { Sequelize } = require("sequelize");
const sequelize = new Sequelize("xxx", "xxx", "xxx", {
host: "localhost",
dialect: postgres,
port: 5000,
});
module.exports = sequelize;
db file

sync is (ironically) an asynchronous operation. You need to await it:
await employees.sync({ alter: true });

Related

how to write migrations to add foreignkey to already existing tables in sequelize

I have this already created two tables called User and Profile.
This is how my model for User looks like..
const Sequelize = require("sequelize");
const db = require("../db");
const User = db.define("User", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: {
type: Sequelize.STRING,
allowNull: true,
},
email: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
validator: {
isEmail: true,
},
},
});
module.exports = User;
and model for Profile looks like..
const Sequelize = require("sequelize");
const User = require("./User");
const db = require("../db");
const Profile = db.define("Profile", {
image: {
type: Sequelize.STRING,
},
description: {
type: Sequelize.TEXT,
},
});
module.exports = Profile;
Now I want to define a one-to-one relationship between User and Profile such that user will recieve a profileId column.
so i am defining it like this
Profile.hasOne(User, {
foreignKey: {
allowNull: false,
},
});
User.belongsTo(Profile);
Now i am not able to figure out how to write migrations for the newly added foreign key
can anyone help me please..
Thanks.
I got the answer. for someone who is confused like me here is the answer
since the User table already exists, migrations for the foreignkey will look like this
module.exports = {
async up(queryInterface, Sequelize) {
return await queryInterface.addColumn("Users", "ProfileId", {
type: Sequelize.INTEGER,
references: {
model: "Profiles",
key: "id",
},
});
},
async down(queryInterface, Sequelize) {
return await queryInterface.removeColumn("Users", "ProfileId", {
type: Sequelize.INTEGER,
references: {
model: "Profiles",
key: "id",
},
});
},
};
the Users in addColumn and removeColumn is the name of the table in which foreignkey was added.
the ProfileId is the name for foreignkey which you would have specified in hasOne.
hope this helps..

Unknown database 'my_db' , errno: 1049,

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.

Sequelize and module.exports

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();

Sequelize Association Error include.model.getTableName is not a function

Hello I am new to nodejs and currently I integrated Sequelize with NodeJs. I make different models and define associations but when I fetch data then I received following error
TypeError: include.model.getTableName is not a function
My Box Model
const Sequelize = require('sequelize');
const PostBox = require("./PostBox");
module.exports = function (sequelize) {
var Box = sequelize.define('box', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
references: {
model: PostBox,
key: "box_id" // this is the `posts.post_id` column - name it according to your posts table definition (the one defined in ./Post)
}
}
}, {timestamp: false});
Box.associate = function (models) {
Box.hasMany(models.PostBox, {targetKey: 'user_posts_id',foreginkey: 'id'});
};
return Box;
};
Post Box Model
const Sequelize = require('sequelize');
var Post = require('./Post');
module.exports = function (sequelize) {
var PostBox = sequelize.define('user_posts_boxes', {
id: {
type: Sequelize.INTEGER,
primaryKey: true
},
user_posts_id: {
type: Sequelize.INTEGER,
references: {
model: Post,
key: "id" // this is the `posts.post_id` column - name it according to your posts table definition (the one defined in ./Post)
}
},
box_id: {
type: Sequelize.INTEGER,
},
user_id: {
type: Sequelize.INTEGER
},
post_type_id: {
type: Sequelize.INTEGER
}
}, {timestamp: false}
);
PostBox.associate = function (models) {
PostBox.belongsTo(models.Post, {targetKey: 'id', foreignKey: 'user_posts_id'});
};
return PostBox;
};
This is my base model from where I am calling associated model
const Sequelize = require('sequelize');
var Box = require('./Box');
const sequelize = new Sequelize('store_db', 'root', 'root', {
host: 'localhost',
dialect: 'mysql'
});
const User = require("./User")(sequelize);
const PostBox = require("./PostBox")(sequelize);
const Post = require("./Post")(sequelize);
function findOneUer() {
return User.findOne({attributes: ['id', 'username']});
}
function findPostById(id) {
var post = PostBox.findOne({
attributes: ['id', "user_posts_id", "box_id"],
where: {id: id},
include: [
{model: Box, required: true}
]
});
return post;
}
module.exports = {findPostById: findPostById};
When I call findPostById(2) method from my base mode then I received this error.

Why sequelize.sync() always return empty models?

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);
});

Resources