how to insert data in mysql table using sequeilze in express.js - mysql

I try to insert data data in mysql table with sequelize but it insert null instead of value
i m trying following below code in my file userController.js
var db = require('../../../../config/db');
var bcrypt = require('bcryptjs');
TBL_USERS = db.connection.define('users');
var usersController = {
register : function(req,res,next){
db.connection.sync().then(function(){
TBL_USERS.create({
username:req.body.username,
email:req.body.email,
password:bcrypt.hashSync(req.body.password),
role_id:2
}).then(function(insertResult){
//console.log("INSERT...............",insertResult);
let send_data = {success:true,status:200,message:"success",data:insertResult};
return res.json(send_data);
})
.catch(function(err){
console.error("query error =>",err);
return ReE(err, 200,' register fail1',err);
});
})
.catch(function(err){
console.error("sync error =>",err);
return ReE(err, 200,'register fail2',err);
});
}
module.exports = usersController;
it return success message , but it only inserted field_id, createdAt and updatedAt
NOTE: i already validate all value with express-validator so i didn't define in
TBL_USERS = db.connection.define('users');
please help me to resolve this

Need to define data types in users.js or your database model file. add two lines as bellow
username: DataTypes.STRING,
password: DataTypes.STRING
There is no reason to not working. thanks

You need to define schema with field name of table

Related

When inserting an array with TypeORM, the order of id that comes out as result?

TypeORM is working on inserting arrays using INSERT.
I'm going to do another task using the IDs that came out as a result of insert.
At this time, the IDs that come out as a result of insert come out in the order of array when insert?
// customRepository.ts
insertArr(nameArr : {name : string}[]){
reuturn this.createQueryBuilder()
.insert()
.into(customTable)
.values(nameArr)
.execute()
}
// service.ts
const connection = getConnection();
const repository = connection.getCustomRepository('customRepository')
const arr = [{name : 'first'},{name : 'second'}]
const result =
await repository.insertArr(
arr
);
console.log('result : ', result);
//Does this result come out in the order of insert?
Thank you!!!

how to dynamically update row in mysql on node express js

this is how i query to update row and it works:
const [rows, meta] = await db.query(
`
UPDATE
Portfolio
SET
title = ?,
infoText = ?,
devPeriod = ?,
tags = ?
WHERE
id = ?
`,
[title, infoText, Number(devPeriod), tags, Number(portfolioId)]
);
return rows;
but sometimes depending on what user wants i have to query to update only specific columns. For example user might want to edit only devPeriod or tags and infoText.
How do i achieve that?
I'd suggest creating an update object that specifies which fields to update and the relevant values. You can then create a query and parameters from this.
The update object can be populated based on user input.
For example:
async function updatePortfolio(db, portfolioId, update) {
const query = "Update Portfolio SET " + Object.keys(update).map(key => `${key} = ?`).join(", ") + " WHERE id = ?";
const parameters = [...Object.values(update), portfolioId];
console.log("updatePortfolio: Running query:", query);
const [rows, meta] = await db.query(query, parameters);
return rows;
}
// Add or remove fields as you require.
update = {
title: "Some Title",
infoText: "Infotext",
devPeriod: 10,
tags: "tags"
}
updatePortfolio(db, 1, update);
// Add or remove fields as you require.
update = {
title: "Some Title",
tags: "tags"
}
updatePortfolio(db, 2, update);
After asking my colleagues for help they introduced my to Knex.js to make dynamic query building easier. So I just went with it.
Have been using it for dynamic queries since then. Works pretty well for this type of task. Configuration is also easy:
import knex from 'knex';
const queryBuilder = knex({ client: 'mysql' });
export default queryBuilder;
Export it and use it anywhere in your project

Why the current time in node js and when i try to input in mysql is different?

I just confuse with this case. I've been try to make sure the time zone in MySql and see the data that out from Date(Date.now()). That's all is correct with my timezone. But when i try to input the data to MySql, and i check in my Database. The time zone is wrong and different with my Time zone. Is there anyone can help me ?
This my code
const Employee = require('../models/employee');
const History = require('../models/history');
async createHistory(employee){
let result;
try {
const checkData = await Employee.findOne({where :
{employeeId : employee.employeeId}
});
if(checkData !== null){
const createData = await History.create({
employeeId : employee.employeeId,
in : Date(Date.now())
});
console.log(date.toLocaleString());
console.log('True')
}else {
result = {message : false}
}
} catch (e) {
logEvent.emit('APP_ERROR',{
logTitle: '[CREATE-HISTORY-ERROR]',
logMessage: e
});
}
return result;
}
The Time in field 'in' is wrong, it should be 14:43
I just get the answer,
The answer is .. because i using Sequelize to store the data to MySql i have to input the time zone in my connection.
Here my code :
const connection = new Sequelize(
{
timezone: "+07:00"
}
);

Sequelize : How to check if a substring exists in a table

Is there a way to check if a particular string exists in a column in a table?
For example, I have a table 'fruits' with two columns, primary key and fruit_name and following rows
1 apple
2 orange
3 pineapple
I have a sample string named apple_shake. I need to check if a substring of this apple_shake exists. The query should return row containing 'apple'
I know how this can be done in mysql query - SQL - Query to find if a string contains part of the value in Column
But through sequelize, following has problem
var sample_fruit_string = "apple_shake";
var gsp_config = await model.fruit.findOne({where: {
fruit_name: {
[Op.like]: sample_fruit_string + '%'
}
}});
Credit to #alx for the SQL I didn't know was possible - this is how you generate the appropriate SQL with Sequelize. Note that this may not be efficient with large datasets.
const sample_fruit_string = "apple_shake";
const gsp_config = await model.fruit.findOne({
attributes: ['id'],
where: Sequelize.where(
Sequelize.fn('LOCATE', Sequelize.col('fruit_name'), sample_fruit_string),
Sequelize.Op.ne,
0
),
logging: true,
});
Generates the following:
SELECT `id` FROM `fruit` AS `fruit` WHERE LOCATE(`fruit_name`, 'apple_shake') != 0 LIMIT 1;
Sequelize has a substring operator which you could use directly to solve this.
var sample_fruit_string = "apple_shake";
var gsp_config = await model.fruit.findOne({where: {
fruit_name: {
[Op.substring]: sample_fruit_string // LIKE '%sample_fruit_string%'
}
}});
var sample_fruit_string = "apple_shake";
var gsp_config = await model.fruit.findOne({where: {
fruit_name: {
[Op.like]: `%${sample_fruit_string}%` // LIKE '%sample_fruit_string%'
// [Op.ilike]: `%${sample_fruit_string}%` // For case sensitive searching
// [Op.substring]: sample_fruit_substring // Has been depreciated in future version of sequelize.
}
}});

After update and saving the model to store without connecting backend gives error

I am trying to update my mode just only store without connecting backend. after it's done successfully I will retrive the updated model using it's id.
for that, I am trying to push my model to store ( updating the existing model in store ) but getting error.
any one hlpe me?
here is my code :
import Ember from 'ember';
export default Ember.Route.extend({
model: function(params) {
if(this.store.hasRecordForId('card-list', params.id)){
return this.store.peekRecord('card-list', params.id );//getting
}
},
actions:{
formValidateBeforeNext:function(){
var model = this.controllerFor(this.routeName).get('model');
var modelId = this.controllerFor(this.routeName).get('model').get("id");
var oneTimeFee = this.controllerFor(this.routeName).get('model').get("oneTimeFee");
var monthlyInstalmentAmount = this.controllerFor(this.routeName).get('model').get("monthlyInstalmentAmount");
console.log( "model would be:-" , JSON.parse(JSON.stringify(model)) );
this.store.push(JSON.parse(model));//updating without connect to backend,but throws error
console.log( "store data", this.store.peekRecord('card-list', modelId ) )
this.transitionTo('cs2i.balance.balanceReview', {id:modelId});
}
}
});
It depends on what serializer you want to use. I'm assuming you're using the default JSONSerializer. If that's the case, here's how you have to push the data into the store.
import Ember from 'ember';
export default Ember.Route.extend({
model: function(params) {
if(this.store.hasRecordForId('card-list', params.id)){
return this.store.peekRecord('card-list', params.id );//getting
}
},
actions:{
formValidateBeforeNext:function(){
var modelData = { //creating a sample data for testing purpose. You can fetch the data as above from your example
id:1,
type:"card-list",
attributes:{
oneTimeFee:1000,
testPayment:2000
}
}
console.log( "model would be:-" , JSON.parse(JSON.stringify(modelData)) );
this.store.push({
data: modelData
});//updating without connect to backend,but throws error
console.log( "store data", this.store.peekRecord('card-list', 1 ) )
this.transitionTo('cs2i.balance.balanceReview', {id:modelId});
}
}
});
Even if it is RestSerializer all you have to do is use this.store.pushPayload and use model name ("cardList") as the key instead of data.
Hope this helps.