Can't get data by id using NodeJS and MySQL - mysql

I am new to NodeJs and I want to get some information by id. Here is my code The controller :
router.get('/machine', function (req, res) {
Machine.getmachine(req.body, function (err, row) {
if (err) {
res.status(400).json(err);
}
else {
res.json(row);
}
});
});
The SQL part :
getmachine: function (Machine, callback) {
return db.query('SELECT * from machine WHERE id=?', [Machine.id], callback);
},
I tried to test it with Postman and I only got {} as a result.
Please, can you tell me why I don't get what I want?

Try something like this instead of reading the body data you should read it as query. or else if you are passing as params you should user req.params('id') to get the id.
router.get('/machine', function (req, res) {
Machine.getmachine(req.query.id, function (err, row) {
if (err) {
res.status(400).json(err);
}
else {
res.json(row);
}
});
});
Edit
According to the url you provided in the comment you can try something like this.
router.get('/machine:id', function (req, res) {
Machine.getmachine(req.params.id, function (err, row) {
if (err) {
res.status(400).json(err);
}
else {
res.json(row);
}
});
});
If you managed to get the id to the back-end then the issue must be with in you sql query. try something like this
getmachine: function (Id, callback) {
return db.query('SELECT * from machine WHERE id=?', Id, callback);
}

Related

How can I condition my router details to show me all the id's?

In this router it managed to show only a specific id, but within that id I would like to show the others that I have in my database.
router.get('/detalles/:id', (req, res) => {
const id = req.params.id;
conexion.query('SELECT * FROM noticias WHERE id=?', [id], (error, results) => {
if (error) {
throw error;
} else {
res.render('detalles', { noticias: results[0], results: results });
}
});
});
At the top I only need the details of a specific id, below I want to show the others.
What I would recommend you is to do a "Get All" route which means that you will take every id. It think it will look like this.
! Warning ! Don't forget to put it before you route '/detalles/:id' to avoid conflict between them so it will not call /detalles/:id without any id.
router.get('/detalles/', (req, res) => {
conexion.query('SELECT * FROM noticias', (error, results) => {
if (error) {
throw error;
} else {
res.render('detalles', { noticias: results, results: results });
}
});
});

Returning undefined from mySQL

I know the database is connecting with the code as, when i console.log(res) with the code below it is returning the correct data,
const orm={
selectAll(){
connection.query('SELECT * FROM burgers', (err,res) => {
if (err) throw err;
console.log(res)
return res;
});
},
Yet when i console.log(burgers) from this function in the code below it is returning an undefined
app.get(`/`, function (req, res) {
const burgers = orm.selectAll();
console.log(burgers)
res.render(`index`, burgers);
});
I understand this may be a very simple answer but i personally just cannot work it out any help is welcomed.
selectAll is using a callback style method inside it. You can not get the response syncronously. You need to either pass the callback to selectAll or change it to use promise like this
function selectAll() {
return new Promise((reoslve, reject) => {
connection.query("SELECT * FROM burgers", (err, res) => {
if (err) {
reject(err);
}
reoslve(res);
});
});
}
You can then use it like this
app.get(`/`, function async (req, res) {
const burgers = await selectAll();
console.log(burgers)
res.render(`index`, burgers);
});
Your selectAll method will not return any value.
query get an lambda callback function as second parameter AND query is asyncron
One way is to return an Promise from selectAll
const orm = {
selectAll(callback) {
return new Promise((resolve, reject) => {
connection.query('SELECT * FROM burgers', (err, res) => {
if (err) {
reject(err);
} else {
resolve(res)
}
})
})
},
Than you can get your result:
app.get(`/`, function (req, res) {
orm.selectAll().then( burgers => {
console.log(burgers)
res.render(`index`, burgers);
});
});

nodejs- unable to return result to controller function

From my Model, I fetch some articles from a MySQL database for a user.
Model
var mysql = require('mysql');
var db = mysql.createPool({
host: 'localhost',
user: 'sampleUser',
password: '',
database: 'sampleDB'
});
fetchArticles: function (user, callback) {
var params = [user.userId];
var query = `SELECT * FROM articles WHERE userId = ? LOCK IN SHARE MODE`;
db.getConnection(function (err, connection) {
if (err) {
throw err;
}
connection.beginTransaction(function (err) {
if (err) {
throw err;
}
return connection.query(query, params, function (err, result) {
if (err) {
connection.rollback(function () {
throw err;
});
}
//console.log(result);
});
});
});
}
This is working and the function fetches the result needed. But it's not returning the result to the controller function (I am returning it but I'm not able to fetch it in the controller function. I guess, I did something wrong here).
When I did console.log(result) this is what I got.
[ RowDataPacket {
status: 'New',
article_code: 13362,
created_date: 2017-10-22T00:30:00.000Z,
type: 'ebook'} ]
My controller function looks like this:
var Articles = require('../models/Articles');
exports.getArticle = function (req, res) {
var articleId = req.body.articleId;
var article = {
userId: userId
};
Articles.fetchArticles(article, function (err, rows) {
if (err) {
res.json({ success: false, message: 'no data found' });
}
else {
res.json({ success: true, articles: rows });
}
});
};
Can anyone help me figure out what mistakes I made here?
I'm pretty new to nodejs. Thanks!
The simple answer is that you're not calling the callback function, anywhere.
Here's the adjusted code:
fetchArticles: function (user, callback) {
var params = [user.userId];
var query = `SELECT * FROM articles WHERE userId = ? LOCK IN SHARE MODE`;
db.getConnection(function (err, connection) {
if (err) {
// An error. Ensure `callback` gets called with the error argument.
return callback(err);
}
connection.beginTransaction(function (err) {
if (err) {
// An error. Ensure `callback` gets called with the error argument.
return callback(err);
}
return connection.query(query, params, function (err, result) {
if (err) {
// An error.
// Rollback
connection.rollback(function () {
// Once the rollback finished, ensure `callback` gets called
// with the error argument.
return callback(err);
});
} else {
// Query success. Call `callback` with results and `null` for error.
//console.log(result);
return callback(null, result);
}
});
});
});
}
There's no point in throwing errors inside the callbacks on the connection methods, since these functions are async.
Ensure you pass the error to the callback instead, and stop execution (using the return statement).
One more thing, without knowing the full requirements of this:
I'm not sure you need transactions for just fetching data from the database, without modifying it; so you can just do the query() and skip on using any beginTransaction(), rollback() and commit() calls.

ExpressJS res.json(data of the logged in user)

I'm building and MEAN stack APP.
exports.show = function(req, res) {
Posts.findById(req.params.id, function (err, post) {
if(err) { return handleError(res, err); }
if(!post) { return res.send(404); }
return res.json(post);
});
};
Can someone explain how can I send just the posts of the logged in user?
Note: post has a author key equal with the user ID
You should probably look to use the req.user property (I assume you're using Passport or something similar):
exports.show = function(req, res) {
Posts.find({author: req.user.id}, function (err, posts) {
if(err) { return handleError(res, err); }
if(!post) { return res.send(404); }
return res.json(posts);
});
};
If req.user.id doesn't work, try console.log() on req.user, and see if it contains the information you need.

xml2js: put parser into a function

I got this code on my NodeJS server:
function GetXML() {
fs.readFile('../slideshow.xml.old', function(err, data) {
parser.parseString(data, function (err, result) {
var json = JSON.stringify(result);
console.log(json);
return json;
});
});
}
The console.log() is working well but this is not:
.get('/', function(req, res) {
res.end(GetXML());
};
It returns undefined which is quite logic because functions are nested (I think ?). But I don't know how to make GetXML() returning a value.
It's returning undefined because you're trying to execute synchronously an asynchronous task. You have to pass a callback to your GetXML() function, like:
function GetXML(cb) {
fs.readFile('../slideshow.xml.old', function(err, data) {
parser.parseString(data, function (err, result) {
var json = JSON.stringify(result);
cb(json);
});
});
}
, and call it properly in your .get function:
.get('/', function(req, res) {
GetXML(function (json) {
res.end(json);
});
};
You should take a look at this article that explains how callbacks work in node.js.
"GetXML" is not returning a value. It can be change to:
function GetXML() {
return fs.readFile('../slideshow.xml.old', function(err, data) {
parser.parseString(data, function (err, result) {
var json = JSON.stringify(result);
console.log(json);
return json;
});
});
}