Sequelize is not throwing error for invalid inputs in findAll and findOne methods - mysql

I have built a nodejs express app that uses sequelize as ORM to handle MySQL transactions. There are no issues in validations for create, update and delete requests however if I try to fetch data using the findOne and findAll method sequelize seems to escape to validate data.
I have tried writing implicit validations for sequelize using validate but it still doesn't work.
This is the code :
getTradeOrder: async (params) => {
try {
// for params: {amount: '500jha'}
// tradeorder is fetched as if the amount's value was 500
let data = await TradeOrder.findOne({ where: params });
// returns data:{id:2, user:"gfa7834djksfyui32", amount:500, ...}
return { status: 200, error: null, data: data };
} catch (err) {
console.log(err);
return {
status: 400,
error: err.message,
};
}
},
listAllTradeOrders: async (params) => {
try {
// for params: {amount: '500jha'}
// tradeorders are fetched as if the amount's value was 500
let tradeOrders = await TradeOrder.findAll({
where: params,
});
// returns tradeorders:[{id:2, user:"gfa7834djksfyui32", amount:500, ...}, ...]
return { status: 200, error: null, data: tradeOrders };
} catch (err) {
console.log(err);
return {
status: 400,
error: err.message,
};
}
},
};
This is the model :
const tradeOrderSchema = {
id: DataTypes.NUMBER,
user: DataTypes.STRING,
amount: DataTypes.NUMBER,
paymentMode: DataTypes.STRING,
units: DataTypes.NUMBER,
bankName: DataTypes.STRING
...
Ideally, sequelize should capture the invalid value and throw an error for invalid value of amount.
If anyone knows why it is not happening or how to add implicit validation except for validate please let me know.

Related

Node.js - CRUD API multi delete ID's from SQL

I have small project with ReactJS + NodeJS + mySQL.
I can't create-receive correct request for multi delete by IDs.
This how I sent request from React to Node ==>
const deleteProductsByIds = () => {
let ids = [];
stateProducts.forEach((d) => {
if (d.select) {
ids.push(d.id);
}
});
axios
.delete(`http://localhost:5000/products/${ids}`)
.then((data) => {
console.log(data);
getProducts();
})
.catch((err) => alert(err));
};
this how I receive request in Node(sequelize)
router.delete('/:ids', deleteProducts);
export const deleteProducts = async (req, res) => {
try {
await Product.destroy({
where: {
id: []
}
});
res.json({
"message": "ProductS Deleted"
});
} catch (error) {
res.json({ message: error.message });
}
in logs I have this data and by message everything fine, but products(301,302,303,304) not deleted.
config: {url: 'http://localhost:5000/products/301,302,303,304',
method: 'delete', headers: {…},
transformRequest: Array(1), transformResponse: Array(1), …}
data: {message: 'ProductS Deleted'}
I try
where: {
id: req.params.ids
}
but ids value undefind
also I try:
const ids = req.params
try {
await Product.destroy({
where: {
id: ids
}
});
message: "Invalid value { ids: '301,302,303,304' }"}
but receive error message.
usual delete request by ID working without any problem.
For example:
export const deleteProduct = async (req, res) => {
try {
await Product.destroy({
where: {
id: req.params.id
}
});
res.json({
"message": "Product Deleted"
});
} catch (error) {
res.json({ message: error.message });
}
}
Please help me, because I can't find so much information about multi delete request with React-Node-mySQL.

Sequelize showing error: Unexpected token u in JSON at position 0

I am trying to update a record in mysql database using sequelize but it is not working.
I am getting this error
Unexpected token u in JSON at position 0
Model
module.exports = sequelize.define("branches", {
address: Sequelize.TEXT(),
company: Sequelize.STRING(),
codeConfig: {
type: Sequelize.STRING,
allowNull: false,
get: function () {
return JSON.parse(this.getDataValue('codeConfig'));
},
set: function (val) {
return this.setDataValue('codeConfig', JSON.stringify(val));
}
},
});
Update function
router.put('/:id', async (req, res) => {
const { address, company} = req.body;
try {
const branches = await Branches.findOne({ where: { code: req.params.id } });
if (!branches) return res.json({ msg: "Branch Not Found" });
Branches.update({ "address": "No. 10 distreet street" }, {
where: {
code: "WHJ5uBdriI"
}
}).then(function (newBranch) {
return res.json({ msg: "Updated" });
});
} catch (error) {
console.error(error.message);
res.status(500).send("Server Error");
}
});
Error output
Add autoJsonMap: false, to your sequelize's dialectOptions
Example:
let sequelize = new Sequelize(DATABASE, USER, PASSWORD, {
// some other options
dialectOptions: {
autoJsonMap: false,
}
});
Reference:
https://github.com/sequelize/sequelize/issues/12583
i have noticed that before sequelize make a field update, it fetches through all fields, and then execute a getter function if exist, so for that i added an if check inside a getter, here is the code now the model.update working:
get: function () {
if(this.getDataValue('codeConfig') !== undefined){
/// appentely sequelize tried to parse the value of 'codeConfig' but its undefined since you are updating only address field.
return JSON.parse(this.getDataValue('codeConfig'));
}
},

error when executing insert with nodejs + sequelize

I have the following function to insert a record in a MySQL database. I am using NodeJS and Sequelize.
await WeatherData.create ({
control_esp_id: req.body.control_esp_id,
variable_id: req.body.variable_id,
read_date: req.body.date,
value: req.body.value
})
.then ((weatherdata) => {
return res.status (200) .json ({
error: false,
message: "Data regarding the Line / Bay / Room successfully registered!",
weatherdata
});
})
.catch ((err) => {
console.log (err);
return res.status (400) .json ({
error: true,
code: 203,
message: err
});
})
However, the following error message is occurring when I execute the function. i have other inserts and they are working perfectly. Only from this type of model that the error is occurring to me:
TypeError: Cannot read property 'length' of undefined
at WeatherData._initValues (backend/node_modules/sequelize/lib/model.js:140:49)
at new Model (backend/node_modules/sequelize/lib/model.js:118:10)
at new WeatherData (backend/src/app/models/WeatherData.js:9:1)
at Function.build (backend/node_modules/sequelize/lib/model.js:2157:12)
at Function.create (backend/node_modules/sequelize/lib/model.js:2207:23)
at store (backend/src/app/controllers/WeatherDataController.js:62:31)
class WeatherData extends Model {
static init(sequelize) {
super.init({
read_date: DataTypes.DATE,
value: DataTypes.DOUBLE,
}, {
sequelize,
});
return this;
}
static associate(models) {
this.belongsTo(models.ControlEsp, {
foreignKey: 'control_esp_id',
as: 'control_esp',
});
this.belongsTo(models.Variable, {
foreignKey: 'variable_id',
as: 'variable',
});
}
}
sequelizePaginate.paginate(WeatherData);
export default WeatherData
Regards

Sequelize read data from create and decrement

As I've read in this article Sequelize increment function returning error
I have done the next code:
exports.create = function (req, res) {
models.sparepart_request.create({
codWO: req.body.codWO,
codSparePart: req.body.codSparePart,
quantity: req.body.quantity,
date_request: req.body.date_request,
codUser: req.body.codUser,
request_return: req.body.request_return,
received: req.body.received
}).then(function (item) {
return models.sparepart.decrement(
'stock', {
by: req.body.quantity,
where: {
codSparePart: req.body.codSparePart
}
}
);
}).then(function (item) {
res.status(200);
res.json(({
success: true,
message: 'Query successful',
data: item //This is null, I need the values from creating
}));
}).catch(function (error) {
logger.error(JSON.stringify(error));
res.json({
success: false,
message: 'Query not successful and error has occured cretaing',
error: error,
stackError: error.stack
});
return res.status(500);
});
The problem is the following:
My JSON answer is the following:
{
"success": true,
"message": "Query successful",
"data": [
[
null,
1
]
]
}
How can I take the value of the create item?
NOTE: I've tried to do a transaction but always return a error or stops and gives me a Time Out error. I don't know how to do a transaction with a instance.
You can use :
returning: true, // to get updated data back
To get result back from update , destroy and other function where it just returns the no of rows affected , like
return models.sparepart.decrement(
'stock', {
by: req.body.quantity,
where: {
codSparePart: req.body.codSparePart
}
returning: true, // to get updated data back
plain: true, // for plain object and not raw data
}
);

Updating sub array in JSON with a REST API in Mean Stack

I'm developing a MEAN stack application and I'm hung up on how to actually update a document that has been saved into the MongoDB already. I've seen that I have to use patch instead of post in my REST API paths, but it's still a little clouded to me. I want to insert a new Package into the Package JSON Array in the User JSON.
Possible Duplicate, but he's overriding a value in the array and not adding a new object into it.
My JSON Schema:
//User schema
const UserSchema = mongoose.Schema({
name: {
type: String
},
email: {
type: String,
require: true
},
username:{
type:String,
required: true
},
password:{
type:String,
required: true
},
packages: [{
from: String,
to: String,
tracking: String
}]
});
My REST API Paths
//Update
router.patch('/update', (req, res) => {
const username = req.body.username;
const packages = req.body.packages;
User.getUserByUsername(username, (err, user) => {
if(!user){
return res.json({success: false, msg: 'User not found'});
} else {
User.addPackages(user, req.body.packages, (err, user) => {
if(err){
res.json({success: false, msg:'Failed to update packages'});
} else {
res.json({success: true, msg:'update packages'});
}
})
}
});
});
My Module's:
module.exports.addPackages = function(user, packages, callback){
User.findOneAndUpdate(
{username:user.username},
{$push: {"packages" : {
"to" : packages.to,
"from" : packages.from,
"tracking" : packages.tracking
}}},
{new:true},
function(err, newPackage){
if (err) throw err;
});
}
module.exports.getUserById = function(id, callback){
User.findById(id, callback);
}
module.exports.getUserByUsername = function(username, callback){
const query = {username: username}
User.findOne(query, callback);
}
They're updating into my MongoDB, but just the object ID and not the values...
db.your_collection.update({},
{$set : {"new_field":1}},
{upsert:false,
multi:true})