Error retrieving Entry with AreaName in node.js - mysql

I am trying to perform a get with multiple parameters in node.js . I have the following files
entry.routes.js
module.exports = app => {
const entry = require("../controlers/entry.controller.js");
// Retrieve a single Entry with Id
app.get("/entry/:Id", entry.findOne);
app.get("/energy/api/ActualTotalLoad/:AreaName/:Resolution/:Year/:Month/:Day", entry.find1a);
};
ActualTotalLoad.model.js
const sql = require("./db.js");
// constructor
const Entry = function(entry) {
this.Id=entry.Id
};
Entry.findByPk = (Id, result) => {
sql.query(`SELECT * FROM ActualTotalLoad WHERE Id = ${Id}`, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
if (res.length) {
console.log("found entry: ", res[0]);
result(null, res[0]);
return;
}
// not found Customer with the id
result({ kind: "not_found" }, null);
});
};
Entry.findBy1a = (AreaName,Resolution,Year,Month,Day,result) => {
sql.query(`SELECT AreaName,AreaTypeCodeId,MapCodeId,ResolutionCodeId,Year,Month,Day FROM ActualTotalLoad WHERE AreaName = ${AreaName} AND ResolutionCodeId = ${Resolution} AND Year = ${Year} AND Month = ${Month} AND Day = ${Day}` , (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
if (res.length) {
console.log("found entry: ", res[0]);
result(null, res[0]);
return;
}
// not found Customer with the id
result({ kind: "not_found" }, null);
});
};
module.exports=Entry;
and the file: entry.controller.js
const Entry = require("../models/ActualTotalLoad.model.js");
// Find a single Customer with a customerId
exports.findOne = (req, res) => {
Entry.findByPk(req.params.Id, (err, data) => {
if (err) {
if (err.kind === "not_found") {
res.status(404).send({
message: `Not found Entry with id ${req.params.Id}.`
});
} else {
res.status(500).send({
message: "Error retrieving Entry with id " + req.params.Id
});
}
} else res.send(data);
});
};
exports.find1a = (req, res) => {
Entry.findBy1a(req.params.AreaName,req.params.Resolution,req.params.Year,req.params.Month,req.params.Day, (err, data) => {
if (err) {
if (err.kind === "not_found") {
res.status(404).send({
message: `Not found Entry with AreaName ${req.params.AreaName}.`
});
} else {
res.status(500).send({
message: "Error retrieving Entry with AreaName " + req.params.AreaName
});
}
} else res.send(data);
});
};
I am trying to perform this get http://localhost:8765/energy/api/ActualTotalLoad/DE-AT-LU/7/2018/1/4
But I get the error "message": "Error retrieving Entry with AreaName DE-AT-LU"
What am I doing wrong?

You should change your WHERE statement like this
SELECT ... WHERE AreaName = "${AreaName}" AND ResolutionCodeId = ${Resolution} AND Year = ${Year} AND Month = ${Month} AND Day = ${Day}
Note: notice the quotes ( "${AreaName}" )
AreaName in your DB schema is problably typed as string (or text), so you need to quote you search criteria as string (surrounding it by " or ')
I assume that ResolutionCodeId, Year Month, and Day are number types, so it's ok to not quote them.

Related

NodeJS/MySQL: Use Results of Previous SELECT Query?

Building a simple ToDo app in React/NodeJS/Express with MySQL. Users join a group ("family" in the code), then tasks are viewable filtered by familyId. To create a task, I first have a query that finds the user's familyId from the Users table, then I want to include that familyId value in the subsequent INSERT query for creating the task row in the Tasks table. My task.model.js is below:
const sql = require("./db.js");
// constructor
const Task = function(task) {
this.title = task.title;
this.familyId = task.familyId;
this.description = task.description;
this.completed = task.completed;
this.startDate = task.startDate;
this.userId = task.userId;
};
Task.create = (task, result) => {
sql.query("SELECT familyId FROM users WHERE userId = ?", task.userId, (err, res) => {
if (err) {
console.log("Error selecting from USERS: ", err);
return result(err, null);
}
sql.query("INSERT INTO tasks (familyId, title, description, completed, startDate) VALUES (?,?,?,?,?)", [result, task.title, task.description, task.completed, task.startDate], (err, res) => {
if (err) {
console.log("Error inserting in TASKS: ", err);
return result(err, null);
}
})
console.log("created task: ", { id: res.insertId, ...task });
return result(null, { id: res.insertId, ...task });
});
};
However, I cannot figure out how to properly use the familyId result of the SELECT query as a parameter in the suqsequent INSERT query. I know the overall syntax works because I can manually plug in an ID value as a parameter and the entire operation completes successfully - I just need to know how to use the resule of the first query in the next.
The way you are using it should work but the problem is you have defined the callback as res but are passing result in the 2nd sql query
sql.query("SELECT familyId FROM users WHERE userId = ?", task.userId, (err, res) => {
if (err) {
console.log("Error selecting from USERS: ", err);
return result(err, null);
}
//res should have the value for the familyId of the given user so in next line pass res not result
sql.query("INSERT INTO tasks (familyId, title, description, completed, startDate) VALUES (?,?,?,?,?)", [res[0].familyId, task.title, task.description, task.completed, task.startDate], (err, res) => {
if (err) {
console.log("Error inserting in TASKS: ", err);
return result(err, null);
}
})
console.log("created task: ", { id: res.insertId, ...task });
return result(null, { id: res.insertId, ...task });
});
SQL returns array in result , so use result[0] to get first Object ,
and then access the object key by result[0].keyName
Task.create = (task, result) => {
sql.query("SELECT familyId FROM users WHERE userId = ?", task.userId, (err, users) => {
if (err) {
console.log("Error selecting from USERS: ", err);
return result(err, null);
}
let familyId = users && users[0] ? users[0].familyId : null;
sql.query("INSERT INTO tasks (familyId, title, description, completed, startDate) VALUES (?,?,?,?,?)", [familyId, task.title, task.description, task.completed, task.startDate], (err, res) => {
if (err) {
console.log("Error inserting in TASKS: ", err);
return result(err, null);
}
})
console.log("created task: ", { id: res.insertId, ...task });
return result(null, { id: res.insertId, ...task });
});
};

NodeJS - Update MySQL Field after fetching new created id

I'm using NodeJS to insert a row into MySQL with a "title", "userid" and "opid" field ;
After insertion, I'd like to use the newly created id and the userid to create a new string called "audioname".
Then I'd like update a field called "audioname" with this new "audioname" string
Here's the code I'm using to create the audioname;
const audiopost = new Audiopost({
title: req.body.title,
userid: req.body.userid,
opid: req.body.opid
});
Audiopost.create(audiopost, (err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while creating the Audiopost."
});
else
var newaudioid = data.id.toString();
var newuserid = data.userid.toString();
var hyphen = "-";
var m4a = ".m4a"
var newaudioname = newuserid + hyphen + newaudioid + m4a;
res.send(newaudioname);
});
};
And here's the model;
const Audiopost = function(audiopost) {
this.userid = audiopost.userid;
this.title = audiopost.title;
this.opid = audiopost.opid;
};
Audiopost.create = (newAudiopost, result) => {
sql.query("INSERT INTO audioposts SET ?", newAudiopost, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("created audiopost: ", { id: res.insertId, ...newAudiopost });
result(null, { id: res.insertId, ...newAudiopost });
});
};
This will help you I believe,
sql.query("INSERT INTO audioposts SET ?", newAudiopost, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
const insertId = res.insertId;
const userId = newAudiopost.userid;
const m4a = ".m4a";
const audioname = ${insertId}-${userId}${m4a}; //You can change this string in any format
sql.query("UPDATE audioposts SET audioname = ? WHERE id = ?", [audioname, insertId], (err, res, fields) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
})
});

NodeJS Json Return id only?

Here's the NodeJS code I'm using to create a customer in my MySql database;
const customer = new Customer({
email: req.body.email,
name: req.body.name,
active: req.body.active
});
Customer.create(customer, (err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while creating the Customer."
});
else res.send(data);
});
};
Heres' the model;
const Customer = function(customer) {
this.email = customer.email;
this.name = customer.name;
this.active = customer.active;
};
Customer.create = (newCustomer, result) => {
sql.query("INSERT INTO customers SET ?", newCustomer, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("created customer: ", { id: res.insertId, ...newCustomer });
result(null, { id: res.insertId, ...newCustomer });
});
};
And here's what I'm getting in return;
{"id":8,"email":"harry#gmail.com","name":"harry","active":1}
How can I get it to return just the id as a plain integer instead of the entire JSON string?
To get the specific property from the object. e.g. id, access it as data.id and id is an number which will be treated as status code in express so toString() is needed to convert it to string
The response should be:
res.send(data.id.toString())

unable to return response after login in node js api

TypeError: res.send is not a function.
I am getting this error when I try to return response after user login successfully.
can anybody help me out from this error.
here is my code:-
exports.login = function(req, res, next) {
let q = "SELECT * from users WHERE email = ?";
let query = sql.query(q,req.body.email, (error, res) => {
if (res.length > 0) {
bcrypt.compare(req.body.password, res[0].password, function(err, result){
if(err) {
console.log('password dost not match');
console.log("error: ", err);
result(null, err);
}
if(result) {
console.log('pasword match');
const jwtToken = jwt.sign({
email: res[0].email,
id: res[0].id
},
'secret',
{
expiresIn: '2h'
});
//tk = jwtToken;
return res.status(200).json({
error:0,
message:'user login successfully',
token:jwtToken
});
}
});
} else {
console.log('error commit');
console.log("error: ", error);
result(null, error);
}
});
};
just change the res from the call back of sq.query to dataResult, because once you send the res.send... then for sure in your case res was the dataResult of the sql.
exports.login = function(req, res, next) {
let q = "SELECT * from users WHERE email = ?";
let query = sql.query(q,req.body.email, (error, dataResult) => {
if(error){
console.log('error commit');
console.log("error: ", error);
res.status(400).send({error});
}
if (dataResult && dataResult.length > 0) {
bcrypt.compare(req.body.password, dataResult[0].password,
function(err, result){
if(err) {
console.log('password dost not match');
console.log("error: ", err);
res.status(400).send({err});
}
if(result) {
console.log('pasword match');
const jwtToken = jwt.sign({
email: dataResult[0].email,
id: dataResult[0].id
},
'secret',
{
expiresIn: '2h'
});
//tk = jwtToken;
return res.status(200).json({
error:0,
message:'user login successfully',
token:jwtToken
});
}
}else{
res.status(400).send({error:'error occured no email
found'});
}
});
});
};

nodejs returning result from functions

Here's how I write my code
model\user.js
'user strict';
var sql = require('./../db.js');
//User object constructor
var User = function(user){
this.email = user.email;
this.name = user.name;
this.gender = user.gender;
this.profileImageType = user.profileImageType;
this.profileImage = user.profileImage;
this.accountType = user.accountType;
this.createdAt = new Date();
};
User.getCountByEmail = function (email, result) {
console.log("entering user.getCountByEmail with")
console.log(email)
sql.query("Select COUNT(*) AS userCount from users where email = ? ", email, function (err, res) {
if(err) {
console.log("error: ", err);
return result(err, null);
}
else{
console.log("user getCountByEmail returns")
console.log(res)
return result(null, res);
}
});
};
model\userController.js
'use strict';
var User = require('./user.js');
exports.list_all_users = function(req,res){
User.getAll(function(err,user){
console.log('controller')
if (err){
res.send(err);
}else{
console.log('res', user)
res.send(user)
}
});
};
exports.getCountByEmail = function(email,res){
User.getCountByEmail(email, function(err,user){
if (err){
console.log('error', err)
return res.send(err)
}else{
console.log('res', user)
console.log(user)
return user;
}
});
};
index.js
var userController = require('./../model/userController.js');
userController.getCountByEmail("miow#email.com",res,function(err,result) {
if (err){
console.log("34 err")
console.log(err)
}else{
console.log("imin userCount: " + result)
}
});
now in my index.js above, the line userController.getCountByEmail is executed, but I want the result to be accessible inside the function. Unfortunately, it seems the code
function(err,result) {
if (err){
console.log("34 err")
console.log(err)
}else{
console.log("imin userCount: " + result)
}
isn't being executed at all. I only got the line
res [ RowDataPacket { userCount: 1 } ]
imin
[ RowDataPacket { userCount: 1 } ]
which is inside userController.js. So how do I get the result from userController.js sent to index.js ?
function(err,result) {
if (err){
console.log("34 err")
console.log(err)
}else{
console.log("imin userCount: " + result)
}
is not executed because in your model/userController getCountByEmail your only pass two parameters (email, res). So when you call this function in your index.js your actually pass three parameters. with the third one being
function(err,result) {
if (err){
console.log("34 err")
console.log(err)
}else{
console.log("imin userCount: " + result)
}
I would do this:
model/userController
exports.getCountByEmail = function(email,res){
User.getCountByEmail(email, function(err,user){
if (err){
console.log('error', err)
return res.send(err)
}else{
console.log('res', user)
console.log(user)
res.send(user);
}
});
};
index.js
userController.getCountByEmail("miow#email.com",res)
But in general the controller take (req, res, next) as parameter and the res is used like a return because it returns a response to the server.