I'm trying to run a simple application with Express, Sequelize, and MySQL
I get this error:
Executing (default): CREATE TABLE IF NOT EXISTS `tasks` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255) NOT NULL, `description` VARCHAR(255) NOT NULL, `status` NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
err: Error
at Query.run (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\sequelize\lib\dialects\mysql\query.js:52:25)
at C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\sequelize\lib\sequelize.js:313:28
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async MySQLQueryInterface.createTable (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\sequelize\lib\dialects\abstract\query-interface.js:94:12)
at async Function.sync (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\sequelize\lib\model.js:939:5)
at async Sequelize.sync (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\sequelize\lib\sequelize.js:377:9) {
name: 'SequelizeDatabaseError',
parent: Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` ' at line 1
at Packet.asError (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\packets\packet.js:728:17)
at Query.execute (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\commands\command.js:29:26)
at Connection.handlePacket (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:456:32)
at PacketParser.onPacket (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:85:12)
at PacketParser.executeStart (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket.<anonymous> (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:92:25)
at Socket.emit (events.js:375:28)
at addChunk (internal/streams/readable.js:290:12)
at readableAddChunk (internal/streams/readable.js:265:9)
at Socket.Readable.push (internal/streams/readable.js:204:10) {
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlState: '42000',
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` ' at line 1",
sql: 'CREATE TABLE IF NOT EXISTS `tasks` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255) NOT NULL, `description` VARCHAR(255) NOT NULL, `status` NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY
(`id`)) ENGINE=InnoDB;',
parameters: undefined
},
original: Error: You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near 'NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` ' at line 1
at Packet.asError (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\packets\packet.js:728:17)
at Query.execute (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\commands\command.js:29:26)
at Connection.handlePacket (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:456:32)
at PacketParser.onPacket (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:85:12)
at PacketParser.executeStart (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket.<anonymous> (C:\Users\Kryolos.Hakeem\desktop\vodafone-tech-test\back-end-v2\node_modules\mysql2\lib\connection.js:92:25)
at Socket.emit (events.js:375:28)
at addChunk (internal/streams/readable.js:290:12)
at readableAddChunk (internal/streams/readable.js:265:9)
at Socket.Readable.push (internal/streams/readable.js:204:10) {
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlState: '42000',
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` ' at line 1",
sql: 'CREATE TABLE IF NOT EXISTS `tasks` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255) NOT NULL, `description` VARCHAR(255) NOT NULL, `status` NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY
(`id`)) ENGINE=InnoDB;',
parameters: undefined
},
sql: 'CREATE TABLE IF NOT EXISTS `tasks` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255) NOT NULL, `description` VARCHAR(255) NOT NULL, `status` NUMBER NOT NULL, `createdBy` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;',
parameters: {}
}
[nodemon] clean exit - waiting for changes before restart
so here is my connection:
const { Sequelize } = require('sequelize');
require('dotenv').config()
const Sequelized = new Sequelize(
process.env.DATABASE_NAME,
process.env.USER_NAME,
process.env.PASSWORD,
{
dialect: 'mysql',
host: process.env.DATABASE_HOST
}
);
module.exports = Sequelized;
and here is my entry-point for the app
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const router = require('./routes/tasks');
const Sequelized = require('./utiles/database');
const app = express();
require('dotenv').config();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(router);
Sequelized.sync()
.then((result) => {
console.log('result: ', result);
app.listen(3001, () => console.log('App is Listining on port 3001'));
})
.catch((err) => {
console.log('err: ', err);
});
and here is my task model definition
const { DataTypes } = require('sequelize');
const Sequelized = require('../utiles/database');
const Task = Sequelized.define('task', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
title: {
type: DataTypes.STRING,
allowNull: false,
},
description: {
type: DataTypes.STRING,
allowNull: false,
},
status: {
type: DataTypes.NUMBER,
allowNull: false,
},
createdBy: {
type: DataTypes.NUMBER,
allowNull: true
}
});
module.exports = Task;
and here is my attempt to run it
const Task = require("../models/task");
exports.CreateTask = (req, res) => {
const { title, description, userId } = req.body;
Task.CreateTask({
title,
description,
createdBy: userId,
status: 1
}).then(res => {
console.log('res: ', res)
}).catch((err) => {
console.log('err: ', err);
})
}
this issue happened only when I tried to use Task, to start creating tasks, I think the issue is re-priducable,
any help is appreciated for sure,
thanks
The problem is that you defined the model Taks and in the last piece of code, you export a function named CreateTask.
But inside this arrow function, you try to create a new Task but you're calling CreateTask again. And you also missed to specifie for title and description what are the keys you want to assign those values.
You should use Task.creat(... like this:
const Task = require("../models/task");
exports.CreateTask = (req, res) => {
const { title, description, userId } = req.body;
Task.create({
title: title,
description: description,
createdBy: userId,
status: 1
}).then(res => {
console.log('res: ', res)
}).catch((err) => {
console.log('err: ', err);
})
}
Related
I am trying to establish One-to-many relation using sequelize, MySQL and Node-Express I am getting the following error.
server is running on port : 8080
Executing (default): SELECT 1+1 AS result
Executing (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'products' AND TABLE_SCHEMA = 'node_sequelize_api_db'
connected to db
Executing (default): CREATE TABLE IF NOT EXISTS `products` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255) NOT NULL, `price` INTEGER, `description` TEXT, `published` TINYINT(1), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `products`
Executing (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'reviews' AND TABLE_SCHEMA = 'node_sequelize_api_db'
Executing (default): CREATE TABLE IF NOT EXISTS `reviews` (`id` INTEGER NOT NULL auto_increment , `rating` INTEGER, `description` TEXT, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `productId` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`productId`) REFERENCES `products` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;
(node:15924) UnhandledPromiseRejectionWarning: Error
at Query.run (/home/grace/Desktop/_SOFTWARE_ENGINEER/FULLSTACK/node_sequelize/node_modules/sequelize/lib/dialects/mysql/query.js:52:25)
at retry (/home/grace/Desktop/_SOFTWARE_ENGINEER/FULLSTACK/node_sequelize/node_modules/sequelize/lib/sequelize.js:314:28)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:15924) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:15924) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
THIS IS MY Model/index.js where the relation happens
require('dotenv').config();
const {Sequelize, DataTypes} = require('sequelize')
const sequelize = new Sequelize(
process.env.DB,
process.env.USER,
process.env.PASSWORD,{
host:process.env.HOST,
dialect: process.env.DIALECT,
operatorsAlias: false,
/*pool:{
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}*/
}
)
sequelize.authenticate()
.then(() =>{
console.log('connected to db')
})
.catch(err =>{
console.log('Error' + err)
})
const db = {}
db.Sequelize = Sequelize
db.sequelize = sequelize
db.products = require('./productModel.js')(sequelize, DataTypes);
db.reviews = require('./reviewModel.js')(sequelize, DataTypes);
//it won't create the table over and over
db.sequelize.sync({force: false})
.then(()=>{
console.log('yes re-sync done!')
})
//implement One-to-Many relationship
db.products.hasMany(db.reviews,{
foreignKey: 'product_id',
as: 'review',
})
db.reviews.belongsTo(db.products,{
foreignKey: 'product_id',
as: 'product'
})
Model/productModel.js
module.exports = (sequelize, DataTypes) => {
return sequelize.define("product", {
title: {
type: DataTypes.STRING,
allowNull: false
},
price: {
type: DataTypes.INTEGER
},
description: {
type: DataTypes.TEXT
},
published: {
type: DataTypes.BOOLEAN
}
})
}
Review Model
module.exports = (sequelize, DataTypes) => {
return sequelize.define("review", {
rating: {
type: DataTypes.INTEGER,
},
description: {
type: DataTypes.TEXT
}
})
}
Product controller
//7. connect 1 to many relation Roduct to Review
const getProductReviews = async (req, res) =>{
try{
const data = await Product.findAll({include: Review})
}catch(e){
console.error(e)
}
}
module.exports ={
addProduct,
getAllProducts,
getOneProduct,
updateProduct,
deleteProduct,
getPublishedProduct,
getProductReviews
}
If I remove the following code from Model/index.js
//implement One-to-Many relationship
db.products.hasMany(db.reviews,{
foreignKey: 'product_id',
as: 'review',
})
db.reviews.belongsTo(db.products,{
foreignKey: 'product_id',
as: 'product'
})
Everything runs smoothly, so I am convinced that the error comes from the relationship I am trying to implement, I went through the documentation try to implement it differently but I am still getting the same error.
In your code you call sync(..) method which returns Promise. And looks like this promise is rejected. So try to replace
db.sequelize.sync({force: false})
.then(()=>{
console.log('yes re-sync done!')
})
with something like
db.sequelize.sync({force: false})
.then(()=>{
console.log('yes re-sync done!')
})
.catch(e=>console.log("Can't syncronize",e));
I keep getting this as Error
D:\node_apps\financeplus>node financeplus.js
App running on Port: 7000
D:\node_apps\financeplus\node_modules\mysql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^
Error: ER_BAD_FIELD_ERROR: Unknown column 'base64str' in 'field list'
at Query.Sequence._packetToError (D:\node_apps\financeplus\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Query.ErrorPacket (D:\node_apps\financeplus\node_modules\mysql\lib\protocol\sequences\Query.js:79:18)
at Protocol._parsePacket (D:\node_apps\financeplus\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (D:\node_apps\financeplus\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (D:\node_apps\financeplus\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (D:\node_apps\financeplus\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (D:\node_apps\financeplus\node_modules\mysql\lib\Connection.js:88:28)
at Socket.<anonymous> (D:\node_apps\financeplus\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:400:28)
at addChunk (internal/streams/readable.js:290:12)
--------------------
at Pool.query (D:\node_apps\financeplus\node_modules\mysql\lib\Pool.js:199:23)
at D:\node_apps\financeplus\financeplus.js:77:8
at Layer.handle [as handle_request] (D:\node_apps\financeplus\node_modules\express\lib\router\layer.js:95:5)
at next (D:\node_apps\financeplus\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\node_apps\financeplus\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\node_apps\financeplus\node_modules\express\lib\router\layer.js:95:5)
at D:\node_apps\financeplus\node_modules\express\lib\router\index.js:281:22
at Function.process_params (D:\node_apps\financeplus\node_modules\express\lib\router\index.js:335:12)
at next (D:\node_apps\financeplus\node_modules\express\lib\router\index.js:275:10)
at urlencodedParser (D:\node_apps\financeplus\node_modules\body-parser\lib\types\urlencoded.js:82:7) {
code: 'ER_BAD_FIELD_ERROR',
errno: 1054,
sqlMessage: "Unknown column 'base64str' in 'field list'",
sqlState: '42S22',
index: 0,
sql: "INSERT INTO financeplusacct (fullname, address, city,state, tel,email,nationalID,gender,birth_date, bal, ccy, accNum, base64str) VALUES ('Allen Hommer','102 Whitewater Road','Smithfield','North Carolina','(919)800-3322','a.hommer#aol.com','A89360','Male','2021-11-03','2500','USD','00343515949','data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD.........')"
}
D:\node_apps\financeplus>
The information is not saved to the Mysql Database. I have created the tables to accomodate base64str And just adding it, it gives me that Error
the code to insert to Database
app.post('/api/createaccount',function(req,res){
var prologue = '00343';
var digits = Math.floor(Math.random() * 900000) + 100000;
var accNum = prologue + digits;
var fullname = req.body.fullname;
var address = req.body.address;
var city = req.body.city;
var state = req.body.state;
var tel = req.body.tel;
var email = req.body.email;
var nationalID = req.body.nationalID;
var gender = req.body.gender;
var birth_date = req.body.birth_date;
var bal = req.body.bal;
var ccy = req.body.ccy;
var base64str = req.body.base64str;
dbConn.query('INSERT INTO financeplusacct (fullname, address, city,state, tel,email,nationalID,gender,birth_date, bal, ccy, accNum, base64str) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',[fullname, address, city,state, tel,email,nationalID,gender,birth_date, bal, ccy, accNum, base64str], function (error, results, fields){
if (error) throw error;
return res.send({error: false,data: results, message: 'Account setup Complete'})
});
});
Now Calling the REST api from React JS front end like this
function createCustomerAcc(){
let base64str = localStorage.getItem('postImage');
let item = {fullname, address, city, state, tel, email, nationalID, gender, birth_date, bal,ccy, base64str};
fetch('http://localhost:7000/api/createaccount',{
method : 'POST',
mode : 'cors',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(item)
}).then((response) => response.json())
.then((responseJson) =>{
if(responseJson.message =='Account setup Complete'){
alert('Account Setup Complete');
}else{
alert(responseJson.message);
}
}).catch((error)=>{
console.error(error);
})
}
Gives me that Error in console. Why is this so? Please what do I have to do in this case? Its firing back the MySQL Error, and I dont get to see where the challenge comes from as even the column exists in the Database. Aand the funny thing is, the Column exists in all areas. Please what am I not getting right?
Edits
The CREATE Table is given as
CREATE TABLE `financeplusacct` (
`id` int(11) NOT NULL,
`fullname` varchar(150) NOT NULL,
`address` varchar(300) NOT NULL,
`city` varchar(150) NOT NULL,
`state` varchar(150) NOT NULL,
`tel` varchar(150) NOT NULL,
`email` varchar(150) NOT NULL,
`nationalID` varchar(150) NOT NULL,
`gender` varchar(150) NOT NULL,
`birth_date` varchar(150) NOT NULL,
`ccy` varchar(150) NOT NULL,
`bal` decimal(18,2) NOT NULL,
`accNum` varchar(150) NOT NULL,
`base64str` text NOT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
`updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
I successfully connected to a local MySQL server using the new x-authentication. I have a products table with the following schema (DDL):
CREATE TABLE `products` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`description_he` text,
`description_en` text,
`display_name_he` varchar(45) DEFAULT NULL,
`display_name_en` varchar(45) DEFAULT NULL,
`image_path` varchar(255) DEFAULT NULL,
`price` smallint unsigned NOT NULL,
`is_visible` tinyint NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COMMENT='contains information about products'
I tried to insert the following javascript object into this table:
Product {
productID: null,
productName: 'product2',
descriptionHE: 'תיאור המוצר',
descriptionEN: 'product description',
displayNameHE: 'מוצר',
displayNameEN: 'Product',
imagePath: 'assets/images/facebook-512.png',
price: 400
}
I did this using the following code:
let table = this.session.getSchema('...').getTable('products')
return table.insert(
'id', 'name', 'description_he', 'description_en', 'display_name_he', 'display_name_en', 'image_path', 'price', 'is_visible')
.values(
5,
product.name,
product.descriptionHE,
product.descriptionEN,
product.displayNameHE,
product.displayNameEN,
product.imagePath,
product.price,
1)
.execute()
.catch((err) => {
console.log(err);
})
This catches the following error:
Error: Wrong number of fields in row being inserted
at SqlResultHandler.BaseHandler.<computed> (C:\Users\...\node_modules\#mysql\xdevapi\lib\Protocol\InboundHandlers\BaseHandler.js:119:17)
at Array.entry (C:\Users\...\node_modules\#mysql\xdevapi\lib\Protocol\InboundHandlers\BaseHandler.js:90:29)
at WorkQueue.process (C:\Users\...\node_modules\#mysql\xdevapi\lib\WorkQueue.js:75:19)
at Client.handleServerMessage (C:\Users\...\node_modules\#mysql\xdevapi\lib\Protocol\Client.js:208:21)
at Client.handleNetworkFragment (C:\Users\...\node_modules\#mysql\xdevapi\lib\Protocol\Client.js:252:14)
at TLSSocket.<anonymous> (C:\Users\...\node_modules\#mysql\xdevapi\lib\Protocol\Client.js:90:36)
at TLSSocket.emit (events.js:315:20)
at addChunk (internal/streams/readable.js:309:12)
at readableAddChunk (internal/streams/readable.js:284:9)
at TLSSocket.Readable.push (internal/streams/readable.js:223:10) {
info: {
severity: 0,
code: 5014,
sqlState: 'HY000',
msg: 'Wrong number of fields in row being inserted'
}
}
I tried playing with the arguments and simplifying the table schema a bit but I can't find the error yet. Do you know how can I debug the query sent to the SQL server to figure out why it's failing?
The problem was that I used product.name instead of product.productName.
Conclusion, use typescript. :)
I'm using the #mysql/xdevapi package with NodeJS and the MySQL 8 docker container.
The error I'm getting is:
Error: invalid input expression
at module.exports (C:\Users\BugHunter\Projects\nines\server\node_modules\#mysql\xdevapi\lib\DevAPI\Util\parseFlexibleParamList.js:43:15)
Here's my table:
CREATE TABLE IF NOT EXISTS `surveyrewards`.`users` (
`id` INT NOT NULL AUTO_INCREMENT,
`firstname` VARCHAR(20) NOT NULL,
`surname` VARCHAR(20) NOT NULL,
`birthday` DATE NULL,
`gender` ENUM("male", "female") NOT NULL,
`email` VARCHAR(255) NOT NULL,
`postcode` VARCHAR(10) NULL,
`is_subscribed` TINYINT NOT NULL DEFAULT 0,
`is_confirmed` TINYINT NOT NULL DEFAULT 0,
`last_mailed` TIMESTAMP NULL,
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE INDEX `email_UNIQUE` (`email` ASC) VISIBLE)
ENGINE = InnoDB;
And my node code using these docs:
require('dotenv').config()
const mysqlx = require('#mysql/xdevapi')
const config = {
host: process.env.MYSQL_HOST ,
user: process.env.MYSQL_USER,
port: parseInt(process.env.MYSQL_PORT),
password: process.env.MYSQL_PASSWORD,
schema: process.env.MYSQL_DATABASE
}
mysqlx.getSession(config)
.then(session => {
console.log(process.env)
const table = session.getSchema(config.schema).getTable('users')
return table
.insert([ 'firstname', 'surname', 'email', 'gender', 'is_subscribed', 'is_confirmed' ])
.values('Bob', 'hope', 'bob#example.com', 'male', 0, 0)
.execute()
})
.then(() => console.log('Works'))
.catch(err => console.warn(err))
The error is vauge and I'm not sure how to progress from here as my code is the same. Any advice?
That is actually a bug, which is why the error message is not clear. :)
Falsy values such as 0 are not currently accepted as valid values() arguments. This should not be the case though. If you feel like it, you can report it via the MySQL bug tracker using the Connector for Node.js category, but you can consider this as being tracked.
One sort of nasty workaround is to use strings instead. Even if the SQL datatype is TINYINT like in your case, it will still work and the value will be "coerced".
return table
.insert([ 'firstname', 'surname', 'email', 'gender', 'is_subscribed', 'is_confirmed' ])
.values('Bob', 'hope', 'bob#example.com', 'male', '0', '0')
.execute()
Disclaimer: I'm the lead dev of the connector.
I have the following model in NodeJS with sequelize and a MySQL database:
var Sequelize = require('sequelize');
var User = sequelize.define('user', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
...
};
I am trying to add a new user to my databse with the below code:
sequelize.transaction().then(function(t) {
User.create({/* User data without id */}, {
transaction: t
}).then(function() {
t.commit();
}).catch(function(error) {
t.rollback();
});
});
After that, I am getting the next error:
Executing (47f19f7b-a02d-4d72-ba7e-d5045520fffb): START TRANSACTION;
Executing (47f19f7b-a02d-4d72-ba7e-d5045520fffb): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Executing (47f19f7b-a02d-4d72-ba7e-d5045520fffb): SET autocommit = 1;
Executing (47f19f7b-a02d-4d72-ba7e-d5045520fffb): INSERT INTO `user` (`id`, /* next fields */) VALUES (DEFAULT, /* next values */);
Executing (47f19f7b-a02d-4d72-ba7e-d5045520fffb): ROLLBACK;
And the error message:
[SequelizeDatabaseError: ER_NO_DEFAULT_FOR_FIELD: Field 'id' doesn't have a default value]
name: 'SequelizeDatabaseError',
message: 'ER_NO_DEFAULT_FOR_FIELD: Field \'id\' doesn\'t have a default value'
However, if I manually set the id value, it works. It seems sequelize is trying to set a default value in the id field, instead setting an autoincrement integer. I have defined this field as autoIncrement in my database too.
How could I do this insertion? Do I have to set the id manually?
EDIT
This is my table definition:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uid` varchar(9) NOT NULL,
`name` varchar(20) NOT NULL,
`email` varchar(30) DEFAULT NULL,
`birthdate` date NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uid_UNIQUE` (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
You must be sure you're not even sending the id key at all.
I have done a quick minimal test and it seemed to work great:
var Sequelize = require('sequelize');
var sequelize = new Sequelize('cake3', 'root', 'root', {
define: {
timestamps: false
},
});
var User = sequelize.define('user1', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: {
type: Sequelize.STRING
}
});
sequelize.transaction().then(function(t) {
User.create({name:'test'}, {
transaction: t
}).then(function() {
t.commit();
}).catch(function(error) {
console.log(error);
t.rollback();
});
});
Table dump:
CREATE TABLE `user1s` (
`id` int(11) NOT NULL,
`name` varchar(20) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
ALTER TABLE `user1s`
ADD PRIMARY KEY (`id`);
ALTER TABLE `user1s`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1;
In migration, add this line of code:
await queryInterface.sequelize.query("ALTER TABLE table_name AUTO_INCREMENT = 1000000;");