NodeJS Json Return id only? - mysql

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())

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 });
});
};

Can't get status

I am making register/login page using nodejs but when it comes to the step it returns json when accessing the database as well as when creating a new database
here is my code
register.js
const bcrypt = require("bcryptjs");
const User = require("../model/user");
const register = async (req, res) => {
const {
username,
password: plainTextPassword,
password_confirmation: someOtherPlaintextPassword,
tel_or_email,
} = req.body;
if (!username || typeof username !== "string") {
return res.json({ status: "error", error: "Invalid username" });
}
if (!plainTextPassword || typeof someOtherPlaintextPassword !== "string") {
return res.json({ status: "error", error: "Invalid password" });
}
User.findOne({ Email: tel_or_email }, async (error, user) => {
if (error) throw error;
if (user) {
console.log(user);
return res.json({
status: "ok",
success: "email is already in use, please enter another email",
});
} else {
const password = await bcrypt.hash(plainTextPassword, 10);
const password_confirmation = await bcrypt.hash(
someOtherPlaintextPassword,
10
);
const user = new User({
Name: username,
Email: tel_or_email,
Password: password,
});
user.save((error, result) => {
if (error) throw error;
console.log(result);
});
return res.json({ status: "ok", success: "user successfully created" });
}
});
};
module.exports = register;
status work in the first return ( return res.json({ status: 'error', error: 'Invalid username'}) )and the second( return res.json({ status: 'error', error: 'Invalid password'}) ) , remaining is not

Cannot read properties of undefined in Nodejs

I'm trying to do a sample register without JWT using MVC in nodejs, express and mysql so when I run my code and I have an error :
TypeError: Cannot read properties of undefined (reading 'firstName') at exports.register
here is my code :
AuthController
const AuthModel = require('../models/Auth')
// Create and Save a new User
exports.register = (req, res) => {
// Validate request
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!"
});
}
// Create user
const user = new AuthModel({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password
});
// Save user in the database
AuthModel.createUser(user, (err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while registring."
});
else res.send(data);
});
};
AuthModel
const AuthModel = function(table){
this.firstName = table.firstName;
this.lastName = table.lastName;
this.email = table.email;
this.password = table.password;
}
AuthModel.createUser = ( newUser, result ) =>{
db.query("INSERT INTO users SET ?", newUser, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("User are registed: ", { id: res.insertId, ...newUser });
result(null, { id: res.insertId, ...newUser });
});
};
It seems to me as if the req.body is undefined. I think you might need something like body-parser, which has been added into the core of Express starting with version 4.
Try adding this middleware to your entrypoint: app.use(express.json());
See more here: http://expressjs.com/en/api.html#express.json
In your exports.register, you .send() if the body is undefined. That doesn't mean the rest of the code won't be executed.
Replace:
res.status(400).send({
message: "Content can not be empty!"
});
by
return res.status(400).send({
message: "Content can not be empty!"
});

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;
}
})
});

Error retrieving Entry with AreaName in node.js

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.