NodeJS - Update MySQL Field after fetching new created id - mysql

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

Related

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

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.

check if username and email already exists with expressjs validator and mysql

I want to check if email already exist in mysql database using express-validator package to do this. The example about checking email is not for mysql database.
The code is submitting form values successfully but the checks are being skipped. This is a middleware but the middleware is not been implemented before inserting into the database.
The solution I currently implemented is from stackoverflow. But still not working for me
router.post("/register",[
body('username').not().isEmpty().isLength({ min: 4 }).trim().escape(),
//check if email is aleady existing in the database
body('email').not().isEmpty().isEmail().normalizeEmail().custom(async (email, {req})=>{
const getEmails = "SELECT * FROM users WHERE email=" + req.body.email;
return await con.query(getEmails, [email], (error, rows, fields)=>{
if(error){
console.log("the email is not ok",error)
}else{
if (rows.length != 0) {
res.redirect('/guests/register');
return Promise.reject("user already exists.");
}else{
return true;
}
}
})
}),//end check if email already exit
body('phone').not().isEmpty().isLength({ min: 6 }),
body('password').not().isEmpty().isLength({ min: 6 }),
//check if password match
body('passwordConfirmation').not().isEmpty().isLength({ min: 6 }).custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error('Password confirmation does not match password');
}
return true;
}),
//check if password match
], async function(req, res, next) {
try{
var usernames = req.body.username;
var emails = req.body.email;
var phones = req.body.phone;
const hashedPassword = await bcrypt.hash(req.body.password, 10);
let sql = "INSERT INTO `users` (username, email, phone, password) VALUES ('" + usernames + "', '" + emails + "', '" + phones + "', '" + hashedPassword + "')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted, ID: " + result.insertId);
res.redirect('/guests/login');
})
}catch{
//console.log("something is wrong", error)
res.redirect('/guests/register');
}
});
This code works for me:
const express = require('express');
const router = express.Router();
const { check,validationResult } = require('express-validator');
const bcrypt = require('bcrypt');
const bcryptRounds = 10;
router.post('/register', [
check('username')
.exists()
.trim()
.matches(/^[a-zA-Z\ö\ç\ş\ı\ğ\ü\Ö\Ç\Ş\İ\Ğ\Ü ]{3,16}$/)
.withMessage('Invalid username!'),
check('mentionName')
.exists()
.trim()
.matches(/^(?=.*[a-z])[a-z0-9_]{3,15}$/)
.custom(async mentionName => {
const value = await isMentionNameInUse(mentionName);
if (value) {
throw new Error('Mention name is already exists!!!');
}
})
.withMessage('Invalid mention name!!!'),
check('email')
.exists()
.isLength({ min: 6, max: 100 })
.isEmail()
.normalizeEmail()
.trim()
.custom(async email => {
const value = await isEmailInUse(email);
if (value) {
throw new Error('Email is already exists!!!');
}
})
.withMessage('Invalid email address!!!'),
check('password')
.exists()
.isLength({ min: 6, max: 16 })
.escape()
.trim()
.withMessage('Invalid password!!!'),
check('rePassword').exists().custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error('The passwords is not same!!!');
}
return true;
})
],
function (req, res) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
} else {
console.log("----->START USER REGISTRATION");
const username = req.body.username;
const mentionName = '#'+req.body.mentionName;
const email = req.body.email;
const pass = req.body.password;
bcrypt.hash(pass, bcryptRounds, function(err, hash) {
console.log("HASH PASS : "+hash);
//INSERT USER
});
}
});
function isMentionNameInUse(mentionName){
var conn = require('../../modules/mysql_db');
return new Promise((resolve, reject) => {
conn.query('SELECT COUNT(*) AS total FROM users_table WHERE m_name = ?', [mentionName], function (error, results, fields) {
if(!error){
console.log("MENTION COUNT : "+results[0].total);
return resolve(results[0].total > 0);
} else {
return reject(new Error('Database error!!'));
}
}
);
});
}
function isEmailInUse(email){
var conn = require('../../modules/mysql_db');
return new Promise((resolve, reject) => {
conn.query('SELECT COUNT(*) AS total FROM users_table WHERE email = ?', [email], function (error, results, fields) {
if(!error){
console.log("EMAIL COUNT : "+results[0].total);
return resolve(results[0].total > 0);
} else {
return reject(new Error('Database error!!'));
}
}
);
});
}

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.