When I insert data into my DB it says that it was successful but upon checking my DB, all of my fields are null. I am getting undefined values on my firstName,lastName, mobile, and email columns.
I'm really having a hard time debugging as I'm pretty new to JS. I hope anyone can point out what's the problem.
This is the model for Guest
var Guest = function(guest) {
this.firstName = guest.firstName;
this.lastName = guest.lastName;
this.mobile = guest.mobile;
this.email = guest.email;
}
// Insert Guest Data to DB
Guest.createGuest = (guestRequestData, result) => {
db.query('INSERT INTO guest SET ? ', guestRequestData, (error, response) => {
if(error){
console.log('Error while inserting data');
result(null, error);
}else{
console.log('Guest created successfully');
result(null, response);
}
})
}
module.exports = Guest;
And this the controller
// Create New Guest
exports.createNewGuest = (request, response) => {
const guestRequestData = new GuestModel(request.body);
console.log('Request Data', guestRequestData);
// Check Null
if(request.body.constructor === Object && Object(request.body).length === 0){
response.send(400).send({success: false, message: 'Please fill all fields'});
}else{
GuestModel.createGuest(guestRequestData, (error, guest) => {
if(error)
response.send(error);
response.json({status: true, message: 'Guest Created Successfully', data: guest.insertId})
})
}
}
There is a clear example how to insert data into MySQL database using node.js: https://www.mysqltutorial.org/mysql-nodejs/insert/
So in your case would look something like this:
db.query('INSERT INTO guest (firstName, lastName, mobile, email) VALUES (?, ?, ?, ?)', guestRequestData, (error, response) => {
if(error){
console.log('Error while inserting data');
result(null, error);
}else{
console.log('Guest created successfully');
result(null, response);
}
})
where the guestRequestData has the following structure:
["Your first name", "Your last name", "Your mobile", "Your email"]
Make sure you convert the guestRequestData to this format.
Related
How can i do this, When a user registers , I would like the endpoint to still go ahead and get back the information which is saved inside the database.For some reason, it does not work as expected
How do i go about this :
My code is looking thus :
app.post("/api/sign-up", async function (req, res) {
dbConn.query(
`select * from accounts where email = ${dbConn.escape(req.body.email)}`,
async function (err, result, fields) {
if (result.length === 0) {
var email = req.body.email;
var phone = req.body.phone;
var password = req.body.password;
var fullname = "NULL";
const hashPass = await bcrypt.hash(password, 12);
dbConn.query(
`insert into accounts(email, phone, password, fullname) values (?,?,?,?)`,
[email, phone, hashPass, fullname],
function (error, results, fields) {
if (error) throw error;
return res.send({
error: false,
data: results[0],
message: "User created Successfully",
});
}
);
} else {
return res.send({
error: true,
message: "User exists",
});
}
}
);
});
Checked thru the internet, i could not find the information needed.
I managed to fix it.
Code looks like this now , and it shows the data inside POST man
app.post("/api/sign-up", async function (req, res) {
dbConn.query(
`select * from accounts where email = ${dbConn.escape(req.body.email)}`,
async function (err, result, fields) {
if (result.length === 0) {
var email = req.body.email;
var phone = req.body.phone;
var password = req.body.password;
var fullname = "NULL";
const hashPass = await bcrypt.hash(password, 12);
dbConn.query(
`insert into accounts(email, phone, password, fullname) values (?,?,?,?)`,
[email, phone, hashPass, fullname],
function (error, results, fields) {
if (error) throw error;
return res.send({
error: false,
email:email,phone:phone,
message: "User created Successfully",
});
//return res.status(201).json({message: 'User created Successfully', "email":email,"phone":phone});
}
);
} else {
return res.send({
error: true,
message: "User exists",
});
}
}
);
});
Thanks to everyone who decided to take a Look :)
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 });
});
};
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.
I have the following Node/Express route which is used to post data to a MySQL server. It first adds a new user to a table and then takes the id of the new user and adds some more info to a profile table. The second query is dependent on the first one so they run sequentially.
I have written the following code and it runs correctly and does the job.
routes.post('/register', (req,res) => {
console.log('api req: ', req.body)
const email = req.body.email
const password = 'test'// req.body.password
if (!email || !password) return res.status(400).json({type: 'error', message: 'Please provide email and password'})
const hash = bcrypt.hash(password, 10)
// console.log('hash is ...', hash )
var sqlquery = "INSERT INTO user (username, first_name, last_name, email, password) VALUES ('test#gmail.com', 'Dan', 'Brown', 'test#gmail.com', 'test')"
db.query(sqlquery, (error, results) => {
if (error) return res.status(400).json({type: 'error', message: error})
if (results.length == 0) {
// do something
} else {
// run another query based on results from previous query
var profilequery = "INSERT INTO userprofile (user_id, address, age) VALUES (" + results.insertId + ", 'test address', 25)"
db.query(profilequery, (error1, results1) => {
if (error) return res.status(400).json({type: 'error1', message: error1})
console.log("profile inserted, ID: " + results1)
})
}
console.log("1 record inserted, ID: " + results.insertId);
res.json({type: 'success', message: 'user registered', results})
return results
})
})
There are two problems:
Problem 1: This code is not asynchronous. I would love to use async/await on this code. Really appreciate if someone can help me convert this into async code.
Problem 2: I have tried to use bcrypt to hash the password. However, if I use the hashed value in the query, the query fails because bcrypt returns a promise and not the actual hashed password. I do I resolve this.
not tested:
asyncQuery = (query, args) => {
return new Promise((resolve, reject) => {
db.query(query, function (err, result, fields) {
if (err)
return reject(err);
resolve(result);
});
});
}
routes.post('/register', (req, res) => {
console.log('api req: ', req.body)
const email = req.body.email
const password = 'test'// req.body.password
if (!email || !password) return res.status(400).json({ type: 'error', message: 'Please provide email and password' })
const hash = bcrypt.hash(password, 10)
// console.log('hash is ...', hash )
const sqlquery = "INSERT INTO user (username, first_name, last_name, email, password) VALUES ('test#gmail.com', 'Dan', 'Brown', 'test#gmail.com', 'test')"
let firstresult, secondresult;
asyncQuery(sqlquery)
.then(rows => {
firstresult = rows;
const profilequery = `INSERT INTO userprofile (user_id, address, age) VALUES ("${rows.insertId}", 'test address', 25)`;
return asyncQuery(profilequery)
})
.then(rows => {
secondresult = rows;
})
.then( () => {
console.log(`firstresult:${firstresult}`)
console.log(`firstresult:${secondresult}`)
res.json({ type: 'success', message: 'user registered', results })
})
.catch(rows => {
console.log(`Error:${rows}`)
})
})
I'm having difficulty setting up passport-facebook with MySQL.
Everywhere I look I find mongodb, and using mongodb one can post the profile._json object into the database but with MySQL you can't.
passport.use(new FacebookStrategy({
clientID : "",
clientSecret : "",
callbackURL : ""
}), function (accessToken, refreshToken, profile, done){
db.query("SELECT * FROM users WHERE facebook_id = ?", [profile.id], function(err, user){
if (err){
return done(err);
}
else if (user.length == 0){
var name = profile.displayName;
var email = profile.emails[0].value;
var username = profile.username;
var provider = "facebook";
var facebook = profile._json;
db.query("INSERT INTO users (name, email, username, provider, token) VALUES (?, ?, ?, ?, ?)",
[name, email, username, provider, /* profile._json?? */], function(err){
})
}
else{
return done(err, user);
}
});
});
What is the contents of profile._json that need to be saved and their types so that I can create fields in MySQL database?
Is there a possibility that maybe I should set up mongodb and save that info there and use MySQL databse for the rest? I am also using google authentication for my API.
Try this
let user= {Facebook_ID: profile.id, First_Name: profile.displayName, FB_Private_Chat_ID: '000001100'};
mysqlconnection.query('INSERT INTO users SET ?', user, (err, res) => {
if(err) throw err;
console.log('Last insert ID:', profile.id);
})