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.
Related
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;
}
})
});
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.
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'});
}
});
});
};
I have tried it through MongoDB, but I can't to use JOIN Query in mongoDB and my project is wide enough. So, Want to Create Restful API in node js in MySQL.
Can anyone suggest the solution
For creating REST API you can go with express JS
var express = require('express');
var app = express();
app.get('/', function (req, res) {
//BELOW-CODE
});
You can connect Mysql by following this code:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
);
});
Note: Install expressJS framework to get started
Happy coding :-)
For MySQL with NodeJS you can use Sequelize, it's an ORM kinda like doctrine in symfony
http://docs.sequelizejs.com/
`'user strict';
var sql = require('./db.js');
//Task object constructor
var Task = function(task){
this.task = task.task;
this.status = task.status;
this.created_at = new Date();
};
Task.createTask = function createUser(newTask, result) {
sql.query("INSERT INTO tasks set ?", newTask, function (err, res) {
if(err) {
console.log("error: ", err);
result(err, null);
}
else{
console.log(res.insertId);
result(null, res.insertId);
}
});
};
Task.getTaskById = function createUser(taskId, result) {
sql.query("Select task from tasks where id = ? ", taskId, function (err, res) {
if(err) {
console.log("error: ", err);
result(err, null);
}
else{
result(null, res);
}
});
};
Task.getAllTask = function getAllTask(result) {
sql.query("Select * from tasks", function (err, res) {
if(err) {
console.log("error: ", err);
result(null, err);
}
else{
console.log('tasks : ', res);
result(null, res);
}
});
};
Task.updateById = function(id, task, result){
sql.query("UPDATE tasks SET task = ? WHERE id = ?", [task.task, id], function (err, res) {
if(err) {
console.log("error: ", err);
result(null, err);
}
else{
result(null, res);
}
});
};
Task.remove = function(id, result){
sql.query("DELETE FROM tasks WHERE id = ?", [id], function (err, res) {
if(err) {
console.log("error: ", err);
result(null, err);
}
else{
result(null, res);
}
});
};
module.exports= Task;
I want to return the MySQL result into a variable.
I tried the following but it's not working, as I am getting an empty variable.
const mysql = require('mysql');
const db = require('../config/db');
const connection = mysql.createConnection(db);
module.exports = class Categories {
constructor (res) {
this.res = res;
}
getCategories() {
connection.query("SELECT * FROM `categories`", (error, results, fields) => {
if (error) throw error;
this.pushResult(results);
});
}
pushResult(value) {
this.res = value;
return this.res;
}
};
Just made a callback function first:
var Categories = {
getCategories: function (callback) {
connection.query("SELECT * FROM `categories`", (error, results, fields) => {
if(error) { console.log(err); callback(true); return; }
callback(false, results);
});
}
};
And then used it with route:
app.get('/api/get_categories', (req, res) => {
categories.getCategories(function (error, results) {
if(error) { res.send(500, "Server Error"); return; }
// Respond with results as JSON
res.send(results);
});
});