Hi everyone I am new to mysql and would like to test if the same genre exist in a database and if it does it returns a status code and if the genre does not exist the genre is added into the database. I am currently having the following issues, it is able to check if the genre exist and return the status code but when entering a different genre it reacts the same way as if the genre exist :
file 1
Insertgenre:function(genre,description,callback){
var dbConn=db.getConnection();
// connects to the mysql database (contains an asyn function that returns a callback)
dbConn.connect(function(err){
if(err){
console.log(err);
return callback(err,result);
}else{
// Query for get all rows from genre table where genre = entered genre
var checkSql = 'SELECT genre FROM genre WHERE genre = ?';
dbConn.query(checkSql, [genre], function(err1, result) {
if(err) {
return callback(err,result);
}else {
// Checking if the result length is more than 0.
if(result.length > 0) {
return callback(err1,result);
}else {
var sql="insert into genre(genre,description) values(?,?)";
dbConn.query(sql,[genre,description],function(err,result){
dbConn.end();
if(err) {
console.log(err);
}
return callback(err,result);
}
}
}
});
file 2
app.post('/genre', function(req,res){
var genre = req.body.genre;
var description = req.body.description;
genreDB.Insertgenre(genre,description,function(err,err1,result){
if(err){
//console.log(err)
res.type('json');
res.statusCode=500;
res.send(`{"Result":"Internal Error"}`);
}if(err1){
console.log(err1)
res.type('json');
res.statusCode=422;
res.send(`{"Result":"The genre name provided already exists"}`);
}
else{
res.type("json");
res.statusCode=204;
//res.send(result);
console.log(result);
res.send(`{"Affected Rows":"${result.affectedRows}"}`);
}
});
});
Your callback function expects err to be a normal database error, and err1 to indicate that the genre already exists.
You need to call callback() with 3 arguments to match what it expects.
You also have a typo. In the second query, the callback function's argument is err1, but you used if(err).
And in file 2, you should use else if(err1) since all these conditions are mutually exclusive.
Insertgenre: function(genre, description, callback) {
var dbConn = db.getConnection();
// connects to the mysql database (contains an asyn function that returns a callback)
dbConn.connect(function(err) {
if (err) {
console.log(err);
return callback(err, false, result);
} else {
// Query for get all rows from genre table where genre = entered genre
var checkSql = 'SELECT genre FROM genre WHERE genre = ?';
dbConn.query(checkSql, [genre], function(err1, result) {
if (err1) {
return callback(err1, false, result);
} else {
// Checking if the result length is more than 0.
if (result.length > 0) {
return callback(null, true, result);
} else {
var sql = "insert into genre(genre,description) values(?,?)";
dbConn.query(sql, [genre, description], function(err, result) {
dbConn.end();
if (err) {
console.log(err);
}
return callback(err, false, result);
}
}
}
});
});
})
Related
I am building a user sign up and crud app. I have a db model.
var valid;
module.exports = {
connectDB: function(){
}
,
findUser: function(req,res) {
}
,
createUser: function(email,name,password){
var role = 'view';
var sql = "INSERT INTO `users`(email, name, password, role) VALUES (" + "'"+email+"'"+","+"'"+name+"'"+","+"'"+password+"'"+","+"'"+role+"'"+")";
db.query(sql, function(err, result){
if(err){
console.log(`FAILED: ${err}`)
return false; // tried setting valid to false
}
else
{
console.log(`User Created`);
valid = true;
}
});
return valid; // this also returns undefined
}
}
I want to be able to return a bool depending up on the succession of the query. I tried returning true/false. I did some searching on why this happens. Firstly there was an explanation about js being asynchronous.
My question is what is the correct way of returning values in function when exporting so that I can use it?
By using promises
createUser: function(email,name,password){
return new Promise(function(resolve,reject){
var role = 'view';
var sql = "INSERT INTO `users`(name, password, role) VALUES (" + "'"+email+"'"+","+"'"+name+"'"+","+"'"+password+"'"+","+"'"+role+"'"+")";
db.query(sql, function(err, result){
if(err){
console.log(`FAILED: ${err}`)
reject(err);
}
else
{
console.log(`User Created`);
resolve();
}
});
})
}
we can now use createUser like so;
db.createUser(email,name,password).then(function(){
console.log('redirect');
res.redirect('/');
}).catch(function(){
console.log('something went wrong');
res.render('signup', { message: 'something went wrong' })
});
I'm trying to create access levels in Node.js using Session. So for example, if the username is "test" it can view a certain page. If the username is "admin" it cannot view that same page. The username is stored in MySQL table "accounts". The table has the column attribute "username". Been trying to try different things but I can't seem to get it to work.
Here's my JS code:
app.get('/ViewPage', function(request, response) {
var connection = request.app.get('pool');
if (request.session.loggedin) {
var username;
connection.query('SELECT username FROM accounts WHERE username = test', function (error, results, fields) {
if (username == "test") {
// do the command here
} else if (username == "admin"){
response.redirect('/');
}
});
} else {
response.redirect('/');
}
});
Edit:
I updated my code as follows but it keeps looping to the "Admin cannot view this page" else if block.
app.get('/Create_Award', function (request, response) {
var connection = request.app.get('pool');
if (request.session.loggedin) {
connection.query('SELECT username FROM accounts', function (error, results, fields) {
{ account: results[0] };
if (error) {
console.log(error);
}
else {
if (results[0].username === "test") {
connection.query('SELECT accounts.id, accounts.username, awardType.id as awardTypeId, awardType.title FROM accounts JOIN awardType WHERE username = ?', [request.session.username], function(error, results, fields) {
response.render('Create_Award.html', { account: results[0], data: results });
console.log('Test account.');
}); //2nd connection
}
else if (results[0].username === "admin") {
response.redirect('/');
console.log('Admin cannot view this page.');
}
else {
response.redirect('/');
}
}
}); //1st connection
} else {
response.redirect('/');
}
});
app.get("/viewpage", async function(req, res) {
var connection = req.app.get("pool");
if (res.session.loggedin) {
try {
const result = await connection.query(
"SELECT * FROM accounts WHERE username = test"
);
if (result[0].username === "test") {
//something
} else if (result[0].username === "admin") {
//something
}
} catch (error) {
//You can log the error
return res.redirect("/");
}
}
return res.redirect("/");
});
There are some things to note here
1) Usage of async/await. It makes the code more readable, since queries can take some time to retrieve the data. Also encapsulating all of it inside a try/catch block so you can handle the error if there's any.
2) Your query callback wasn't used. You should use the results argument to retrieve the data in a callback-way.
3) While this is my opinion, always try to return a response, otherwise you may get "Routing error: Can't set headers after they are sent"
You are never populating your var username as it will always will be undefined and your code will go to else block
app.get('/ViewPage', function (request, response) {
var connection = request.app.get('pool');
if (request.session.loggedin) {
connection.query('SELECT username FROM accounts WHERE username = test', function (error, results, fields) {
if (error) {
console.log(error);
}
else {
if (results[0].username === "test") {
response.redirect('/myCustom');
}
else if (results[0].username === "admin") {
response.redirect('/');
}
else {
response.redirect('/');
}
}
});
} else {
response.redirect('/');
}
});
Update your code and it will work
Edit- From what I can see understand from your updated code, the only thing incorrect is how you are using res.render. have a look here, it takes a callback function
Try this in your code and let me know if it works
response.render('Create_Award.html', { account: results[0], data: results },(err,html)=>{
res.send(html)
});
So i have implemented a mongodb on my nodejs server. And what I have done is store users via:
function insertUser() {
var collection = dbb.collection('user');
var user1 = {name: user, token: token};
collection.insert(user1, function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
});
}
function findUserByName(devName) {
var collection = dbb.collection('user');
collection.find({name: devName}).toArray(function (err, result) {
if (err) {
console.log(err);
} else if (result.length) {
console.log('Found: ', result);
selectedUserToken = result.token;
} else {
console.log('No document found');
insertUser();
}
dbb.close();
});
}
So result will equal:
Found: [ { _id: 57be1cadc281c03ea116c9ab,
name: 'Austin Hunter',
token: 'dJyXVjMJk08kXWrua8SUjKb....SxACihKZoR53y_wOZmcFNKMmD5q99QNvsp3flL' } ]
My question is, how can I get that token out to equal selectedUserToken so I can send a push notification with gcm? Right now result.token is undefined.
You should use findOne() instead of find() since you only expect a single result back:
function findUserByName(devName) {
var collection = dbb.collection('user');
collection.findOne({name: devName}, function (err, result) {
if (err) {
console.log(err);
} else if (result) {
console.log('Found: ', result);
selectedUserToken = result.token;
} else {
console.log('No document found');
insertUser();
}
dbb.close();
});
}
But if you wanted to leave your code as is with the find() you would just retrieve the first element of the resulting array retrieved by find()
function findUserByName(devName) {
var collection = dbb.collection('user');
collection.find({name: devName}).toArray(function (err, result) {
if (err) {
console.log(err);
} else if (result.length) {
console.log('Found: ', result);
selectedUserToken = result[0].token;
} else {
console.log('No document found');
insertUser();
}
dbb.close();
});
}
Maybe result[0].token, because result is an array of user items.
I did a restful delete to remove a record by id.. It didn't return me any error, but the record isn't get removed in my collection
my route
app.delete('/api/genres/:id',function(req,res){
var id = req.params._id;
var genre = req.body;
Genres.deleteGenre(id, function(err,genre){
if(err){
throw err;
}
res.json(genre)
})
});
my model (I'm using mongoose)
//Delete Genre
module.exports.deleteGenre = function (id, callback) {
var query = {_id: id};
Genre.remove(query, callback);
}
it even return ok status with
{"ok":1,"n":0}
app.delete('/api/genres/:id',function(req,res){
var id = req.params.id;
Genres.deleteGenre(id, function(err,genre){
if(err){
throw err;
}
res.json(genre)
})
});
//Delete Genre
module.exports.deleteGenre = function (id, callback) {
var query = {_id: id};
//use this to findByIdAndRemove in mongoose, it will work
Genre.findByIdAndRemove(query, callback);
}
you don't need to take anything in var genre = req.body
Try this!!!
Happy Coding!!!
use findById to get the document first then you will be able to remove them
Genre.findById(req.params.id, function(err, genre){
if(err) { return res.send(500, err); }
genre.remove(function(err){
if(err) { return res.send(500, err); }
return res.send(204);
});
});
After running the code, it shows "products is not defined".Where products is supposed to be result of find() query in "products" collection in mongodb. When I run the same query outside the loop, it shows the desired result. How to solve the problem.
Likes.find({"user_id": data.user_id},function(err, likes) {
if(likes === undefined) return res.notFound();
if (err) return next(err);
likedProducts = likes;
for(var key in likedProducts)
{
product_ids = likedProducts[key]['product_id'];
console.log(product_ids);
Products.find({"_id": product_ids},myCallback(err,products));
}
// return res.json(200, {'success': true, 'count': countNo, 'data': productDetails});
function myCallback(err, product_found) {
if(product_found === undefined) return res.notFound();
if (err) return next(err);
// productDetails = product_found;
console.log(product_found);
}
});