'Table not found' error when inserting row. Sequelize and nodejs - mysql

When I'm trying to import user into database with User.create(), sequelize trows me error that says that table doesn't exist. Even tho I created a table line above the create function. My goal is to add user without using .then() function on .sync function.
I've tried to put sync function in await as I imagined that the sync function takes longer to finish.
// imports ...
// Connecting to database
// Creating ORM object
const db = new sequelize(format("%s://%s:%s#%s:%s/%s", gvars.db_soft, gvars.db_user, gvars.db_pass, gvars.db_host, gvars.db_port, gvars.db_daba));
db.authenticate().then(() => {
console.log("Connection established.");
}).catch(err => {
console.error(err);
});
// Define users table
const User = db.define("users", {
firstName: {
type: sequelize.STRING,
allowNull: false
},
lastName: {
type: sequelize.STRING,
allowNull: false
}}, { freezeTableName: true,
});
db.sync({ force: true }).then(() => { console.log("Table created."); });
User.create({
firstName: "Milan",
lastName: "Vjestica"
});
//...starting app
I expect for user to be added in table.

You have to use promise in sequelize as it is a promised based ORM,try following changes:
User.create({ firstName: "Milan",lastName: "Vjestica"}).then(function(user)
{
console.log(user.get('firstName'));
console.log(user.get('lastName'));
});

Related

Sequelize associations not generating foreign key

Sequelize is not creating the foreign key automatically, and is throwing a "no column "userId" in "fieldset"" error. I try to provide all the information down below. Im completely stuck on where to go from here as my code is 100% correct. (Read below)
So i have a Product and User model. both before were working fine. I added some code to set up the relationship:
Product.belongsTo(User, { constraints: true, onUpdate: "CASCADE" });
User.hasMany(Product);
I also, when syncing the db, have used {force: true} and removed it after tables were refreshed. Ive tried restarting pc after these steps, restarting workbench, creating a new database and changing connection to connect to fresh one, still it doesnt put a "userId" column in my product schema.
Ive had this code checked by two people so far and they confirm my syntax is fine, and are equally baffled. Im also confident myself that its not incorrect because im following a reputable course and i've now had to copy and paste his code in replacement to mine just incase, which didnt work.
Product model:
const Sequelize = require("sequelize");
const sequelize = require("../util/database");
const Product = sequelize.define("product", {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
title: Sequelize.STRING,
price: {
type: Sequelize.DOUBLE,
allowNull: false,
},
image_url: {
type: Sequelize.STRING,
allowNull: false,
},
description: {
type: Sequelize.STRING,
allowNull: false,
},
});
module.exports = Product;
User model:
const Sequelize = require("sequelize");
const sequelize = require("../util/database");
const User = sequelize.define("user", {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
name: Sequelize.STRING,
email: Sequelize.STRING,
});
module.exports = User;
Syncing code (I create a test user as the course is at a stage where we are testing we can make one):
// db.sync({ force: true })
db.sync()
.then((result) => {
return User.findByPk(1);
// console.log(result);
})
.then((user) => {
if (!user) {
return User.create({ name: "Max", email: "test#test.com" });
}
return user;
})
.then((user) => {
app.listen(5000);
})
.catch((err) => {
console.log(err);
});
The connection is 100% connected as things happen to the tables in my database, just the "userId" column which sequelize should auto-generate from my associations doesnt come up.
Also have tried putting in a foreignKey: "userId" in my Product.belongsTo() line of code to try to implicitly set it. That didnt even work.
Therefore im stuck and cannot continue with my sql code.
Github repo if need further code:
https://github.com/NinjaInShade/online-shop
I tried your code with some modifications about associations and foreign keys and you have two ways to create a column userId and a foreign key:
Add a userId field definition to Product model with references option like this:
userId: {
allowNull: true,
type: Sequelize.INTEGER,
references: {
model: 'users',
key: 'id'
}
}
Synchronize models individually using their sync method:
User.sync({ force: true })
.then(() => {
Product.sync({ force: true }).then(() => {
app.listen(5000);
})
})
Unfortunately the official documentation does not clarify why sync method in Sequelize acts differently in comparison with sync of separate models.
Usually I use migrations and that's why I don't have this issue.

Sequelize Create or FindOrCreate never creates new records, only updates previous ones

When I use sequelize create it always updates the data in the table instead of creating a new one (id is auto increment)
When I ran the same command from mysql workbench it creates the new data correctly. Maybe i'm missing something in my setup...
Sequelize version: sequelize:^5.22.3
Mysql Version: 5.5.62
model:
const Merchants = sequelize.define('merchant', {
merchant_id: { type: Sequelize.STRING(12), allowNull: false },
shop_id: { type: Sequelize.STRING(75), allowNull: false },
status: { type: Sequelize.TINYINT(4), allowNull: false },
credits: { type: Sequelize.INTEGER(11), allowNull: false },
});
create:
Merchants.create({
merchant_id: getNewMerchantID(),
shop_id: shop_id,
status: status,
credits: credits
}).then(merchants => {
console.log(` created merchant: ${shop_id}`);
}).catch(error => {
console.log(` error creating merchant: ${error}`);
})
Console log
Executing (default): SHOW INDEX FROM `merchants`
Executing (default): INSERT INTO `merchants` (`id`,`merchant_id`,`shop_id`,`status`,`credits`) VALUES (DEFAULT,?,?,?,?);
[merchantController] created merchant: SHOP_ID1
Btw I have the same problem with findOneOrCreate, it nevers inserts a new record, always updates the last record that was on the db
findOrCreate
try {
//check if exists
const [merchant, created] = await Merchants.findOrCreate({
where: { shop_id: shop_id },//find this
defaults: {//or create this
merchant_id: getNewMerchantID(),
//shop_id: shop_id, // does not need to repeat, its in the where clause
status: status,
credits: credits
}
});
console.log(`[Merchants] created merchant: ${shop_id} [${created}]`);
return created;
} catch (error) {
console.log(`[Merchants] error creating Merchants: ${error}`);
return false;
}
Found the problem
I was calling the code to create a new record of this model inside the promise from sequelize.sync, that apparently was always dropping the table and inserting new data what made it looks like it was overwriting
sequelize.sync({ force: true }).then(syncRes => {
createMerchant("SHOP_ID1", 1, 999, "TOKEN");
}).catch(error => {
console.log(`sequelize synch error: ${error}`);
});

Sequelize in Nodejs creating duplicate tables upon app start

Ok. Landscape: Node, MySql, Sequelize
Issue: After creating a new data model & migration (node migrate.js which creates just fine), upon app start Sequelize creates a duplicate Table (and also forwards form data to the new table).
Ex: db.virtual_class is the main table, and upon start, db.virtual_classes is also created.
My model:
const Sequelize = require('sequelize');
const sequelize = require('../sequelize');
const model = sequelize.define('virtual_class', {
id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
style: Sequelize.STRING, // e.g. Style of class
description: Sequelize.STRING(1024), // e.g. class Details
jwt_secret: Sequelize.STRING, // e.g. rando string to be used to gen unique keys for every room
});
module.exports = model;
I've isolated what I think is the issue - I'm including the model in a variable on my index controller for my functions.
const Virtual_class = require('./model');
const classQuery = require('./classQuery');
async function addClass({ style, description, secret }) {
const vClass = await Virtual_class.create({
style,
description,
jwt_secret: secret,
}, { raw: true });
return classQuery(vClass);
}
module.exports = {
addClass,
};
Class Query function to return the data in a usable object:
function classQuery(queryResult) {
if (!queryResult) {
return null;
}
return {
id: queryResult.id,
style: queryResult.style,
description: queryResult.description,
secret: queryResult.jwt_secret,
};
}
module.exports = classQuery;
and the migration:
module.exports = {
up: (sequelize, Sequelize) => sequelize.getQueryInterface().createTable('virtual_class', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
style: {
type: Sequelize.STRING,
},
description: {
type: Sequelize.STRING,
},
jwt_secret: {
type: Sequelize.STRING,
},
createdAt: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.fn('now'),
},
updatedAt: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.fn('now'),
},
}),
down: sequelize => sequelize.getQueryInterface().dropTable('virtual_class'),
};
Net result is fine before I run app - DB shows new table, After running app - DB shows dup table.
I'm a relative noob, and been wracking my brain (and trying to find solutions here) to the problem. I've done this before with other migrations with no issue.
Any advice is appreciated! Thanks!
DOH! For those who are new like me - Sequelize automatically creates plural tables by default, You can force the override tp singular table names.

Async await in mysql seeding does not run

I am trying to seed my MySQL database. I am using the Sequelize ORM. In my index.js file which is in the models folder, I have the code to run the realSync() function for every model as such :
const syncDB = async () => {
await db['Meal'].realSync();
await db['User'].realSync();
}
syncDB();
And in my 'Meal' file, I have the following:
const mealSeeds = require("../scripts/mealSeeds");
module.exports = (sequelize, DataTypes) => {
let Meal = sequelize.define("Meal", {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: DataTypes.STRING,
type: DataTypes.STRING,
description: DataTypes.STRING,
photo_URL: DataTypes.STRING,
allergen_dairy: DataTypes.BOOLEAN,
allergen_treenuts: DataTypes.BOOLEAN,
allergen_peanuts: DataTypes.BOOLEAN,
allergen_wheat: DataTypes.BOOLEAN,
allergen_fish: DataTypes.BOOLEAN,
allergen_crustaceanshellfish: DataTypes.BOOLEAN,
allergen_eggs: DataTypes.BOOLEAN,
allergen_soya: DataTypes.BOOLEAN,
date_available: DataTypes.DATE,
time_available: DataTypes.TIME,
quantity: DataTypes.INTEGER,
zipcodes: DataTypes.JSON,
catererId: {
field: "CatererId",
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 0
}
})
Meal.associate = function (models) {
Meal.belongsTo(models.User, {
foreignKey: "catererId",
targetKey: "id"
})
}
// // Insert the meal seed data
Meal.realSync = async () => {
await Meal.sync()
return await Meal.bulkCreate(mealSeeds,
{ignoreDuplicates: true}
);
};
return Meal;
}
Where the Meal.realSync is supposed to seed the Meals table with data from the mealSeeds.js file in the scripts directory. (And I have a User.js file with the user table fields and a similar .realSync() function for the User table. And this function is working just fine, and users are being seeded into the db).
This function was working fine for weeks, as I was building the project, and recently after changing some of the fields in the 'Meal' table, it no longer works. My previous research shows that by calling the realSync() function asynchronously in the index.js file, it will run and wait for the Meal realSync() function to complete before running the User realSync() function. I am not sure why it no longer runs the first function at all. Any help would be greatly appreciated.
Solved-I figured out that my seed data did not contain a foreign key reference.

Unique email address with Sequelize

I'm running ExpressJS with Sequelize/MySQL and trying very hard to get a simple validator check working for unique email address.
Here is my user model. And for the life of me I don't understand why this is allowing records that have duplicate email address. Surely the email.unique=true would be preventing this.
'use strict';
module.exports = (sequelize, DataTypes) => {
var User = sequelize.define('User', {
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: {
msg: "Must be a valid email address",
}
}
}
}, {
indexes: [{
fields: ['email'],
unique: true,
}]
});
return User;
};
Any help appreciated.
EDIT:
As requested here is the controller code for create user.
const User = require('../models').User;
exports.create = (req, res) => {
User.create( req.body )
.then( user => {
res.json( user );
})
.catch( errors => {
res.json({ errors: errors.errors });
});
};
One way to solve this is by using sequelize.sync() to create your table according to the schema specified in the model if the table exists then you should pass {force: true} to the sync method, the table will be dropped and a new one will be created.
though using sequelize.sync() is not highly recommended especially in production due to issues with migration files etc, you can google than for more details.