login: function (req, res) {
var username = req.param('username');
var password = req.param('password');
User.findOne({username: username}, function (err, user) {
if (err || !user) {
return res.status('401').send("User with username \"" + username + "\" not found. Are you registered?");
}
...
Gives me undefined for the user object and I always end up in the error statement. The username variable has the correct value. The method, where I create records, works (so my connection with the DB is alright), and when I look into the DB, the record is there, with all the correct data.
I also tried User.find().where({username: username}).exec(function (err, user) { with no success...
Any suggestions about where can I look into (debugging or smth) or what might be the cause of the problem?
Jonathan's comment to inspect err pointed me in the right direction. My User model was as follows:
attributes: {
// Relations
passports: {
model: 'Passport'
},
//... other attributes
and I also have the relation belongsTo declared in the Passport model. The err was giving Details: Error: ER_BAD_FIELD_ERROR: Unknown column 'users.passports' in 'field list', and of course in my user table in the database I did not have the passports column.
Conclusion: I had unnecessary entity relation declaration in the User model. This was working fine with MongoDB, but apparently with MySQL things quite different.
Related
I am new to Node.js and SQL programming and I encountered a problem where I don't know how to get, if the user already exists in the database. I tried to check if (selectUsername.length = username) and it didn't work. I also tried with the version from a previous post in stackoverflow
const selectUsername = conn.query("SELECT username FROM user WHERE username= "+ username, function (err, row){
if (row && row.length) {
console.log('Case row was found!');
} else {
console.log('No case row was found :( !', err);
}
})
Username is a variable where my username from form was inserted.
I always get the error Unknown column 'username' in 'where clause'
I have a register form and I want to check if a user already exists so there are no multiple users in the database, so that I can show an error if a user already exists.
Don't substitute a variable into the SQL, use a placeholder and a parameter array.
const selectUsername = conn.query("SELECT username FROM user WHERE username= ?", [username], function (err, row){
I have been trying to setup my Nodejs MySQL database configuration. I found this passport.js config for MySQL on Github. The config works properly but there is a part that I do not understand.
var insertQuery = "INSERT INTO users ( email, password ) values ('" + email +"','"+ password +"')";
console.log(insertQuery);
connection.query(insertQuery,function(err,rows){
newUserMysql.id = rows.insertId;
return done(null, newUserMysql);
});
I am confused about the insertID field. The table I am using does not have a field called insertID. It does however have a field named ID. I tried changing that line to
newUserMysql.id = rows.Id;
bu doing so gives me:
Error: Failed to serialize user into session
Leaving it as it is gives me no error
Looks like insertID has nothing to do with the ID field of my table but I do not understand what it means
That probably represents LAST_INSERT_ID() which is the ID of the last row inserted.
The response of an INSERT is not "rows" but a result object, so maybe better named it'd be:
connection.query("...", function(err, result) {
newUserMysql.id = result.insertId;
return done(null, newUserMysql);
});
It's important to note that using Promises dramatically simplifies your code, and async/await can take that even further. This could be as simple as:
let result = await connection.query("...");
newUserMysql.id = result.insertId;
return newUserMysql;
Where that's inside an async function with a Promise-driven database library like Sequelize. You're not handling the potential errors in your first case. In the second you'll get exceptions which will wake you up when there's problems.
I have a problem I need help with a question. So the problem is I have a route to display all rows of my students table and it works, but know when I try the code below to search for a specific student_id I get:
"Failed to query for users: Error: ER_BAD_FIELD_ERROR: Unknown column 'undefined' in 'where clause'"
I have tried the queryString as:
My table has student_id, firstName, lastName, checkIn, and checkOut as columns.
They are all VARCHARS.
queryString = SELECT * FROM students WHERE student_id = ${id}
queryString = SELECT * FROM students WHERE student_id = ? and then getConnection().query(queryString, [id], (err, rows, fields) => {
But I get the same error, I would really appreciate the help.
The question that I have would be implementing after all my different search routes work as intended to display the data nicely in html, but I'm new to this and I can't find anything to help me with this problem. I would like it to display as a list almost like MySQL displays it. Is that possible? I'm using the ejs view engine as my html pages.
// Route to search by id
router.get("/searchById", (req, res) => {
const id = req.body.id
queryString = `SELECT * FROM students WHERE student_id = ${id}`
getConnection().query(queryString, (err, rows, fields) => {
// If error occures
if(err) {
console.log("Failed to query for users: " + err)
res.sendStatus(500)
return
}
if(rows) {
console.log(rows)
console.log("We fetched Students successfully")
res.json(rows)
}
})
})
For GET request you should use req.query.id
For post request you should use req.body.id
In your code you have used get request and tried to fetch req.body.id
I am using Auth0 for a login service but I have a need to add a user to a database in MySQL every time an account is registered through Auth0.
They give this following script template but I am a newbie and need help debugging and understanding it. My specific questions are detailed as comments:
function create(user, callback) {
var connection = mysql({
host: 'localhost', //what should this be?
user: 'KNOWN/Understood',
password: 'KNOWN/Understood',
database: 'KNOWN/Understood'
});
connection.connect();
var query = "INSERT INTO users SET ?"; //what does this do?
bcrypt.hash(user.password, 10, function (err, hash) { //what does this do?
if (err) { return callback(err); }
var insert = {
password: hash,
email: user.email
};
connection.query(query, insert, function (err, results) {
if (err) return callback(err);
if (results.length === 0) return callback();
callback(null);
});
});
}
Is there anything else I need to change for this script or understand or call in for it to work?
I often get the error missing username for Database connection with requires_username enabled and I'm unsure what this means.
I'm assuming you already went through this tutorial on custom databases so let's address your specific questions.
host: 'localhost' // What should this be?
This and the other properties of this object define the way to connect to your custom MySQL database. The database needs to be reached from within Auth0 servers so this needs to be a host name accessible from the Internet.
"INSERT INTO users SET ?"; // What does this do?
This defines an SQL insert command that uses ? as a placeholder for later substitution.
If you see where this query is later used, you will noticed it's invoked with an additional insert object parameter that will cause the above query to be expanded into something like:
INSERT INTO users SET email = 'user#example.com', password = 'asdf34ASws'
bcrypt.hash(user.password, 10, function (err, hash) // What does this do?
This hashes the user provided password so that it's not stored in plain text in the database.
If you chose to require a username in addition to email you need to address this in your custom scripts as I believe the default templates assume that only email will be used.
This means that when creating the user in your database you also need to store the username and in the script to verify a user you also need to return the username.
I am trying to use redis to store a list of users and weather or not they are online or offline and displaying that information to other users.
I am fairly new to node and I believe that I need to use either a list or sorted sets.
when it gets to the console.log(reply); line it only shows "Object"
I think I need to loop through the results of the query to build the list but I am not really sure 1) how to loop through the results directly in the server application and 2) how to build the list or sorted set based on that query.
Any advice or suggestions would be greatly appreciated.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'users'
});
var redis = require('redis')
, client = redis.createClient();
connection.connect();
connection.query('SELECT * FROM user_profile', function(err, rows, fields)
{
if (err) throw err;
client.set('string key', rows[0], redis.print);
client.get("string key", function (err, reply) {
console.log(reply);
});
});
connection.end();
1) I assume rows contains an array of objects, each object representing a user data record.
client.set('string key', rows[0], redis.print);
is storing the whole first object of rows array, you can use a foreach statement to loop over all values returned.
You are saving the whole object in redis, but you only need the online/offline state 1 or 0. Besides, you can store only strings in redis keys (see Redis Keys Docs and Redis Set Docs)
2) You don't need a list or sorted sets only for online/offline state of a user, unless you need some sorting operations later.
You can use simple keys, I suggest using a pattern like this for key name: "user:".
// assuming that user_name property exists, holds username data "david" and it's unique
client.set("user:"+row[0].user_name, 0, redis.print); // stores key "user:david" = "0";`
Then to retrieve it use:
client.get("user:"+row[0].user_name);
So, your sql query callback function could look like this:
function(err, rows, fields) {
if (err) throw err;
rows.forEach(function(element, index, array){
client.set('user:'+element.user_name, 0, redis.print);
client.get("user:"+element.user_name, function (err, reply) {
console.log(reply);
});
});
}
Please note that the user name must be unique. You can use user ID's if not