I wrote a nodejs Server.
app.get("/admin", function (req, res) {
var connection, value;
connection = mysql.createConnection({
host: "******",
user: "*****",
password: "****",
database: "YaAMP",
insecureAuth: true
});
value = mySQLgetValue("SELECT property, value FROM config WHERE property = 'primeMult'", connection);
console.log("Return Value" + value); //returns "[object Object]"
connection.end();
return res.render("admin", {
title: "YaAMP"
});
});
And a mySQLgetValue Function to get the a value from the MySQL Database, which should return a specific value from the DB.
mySQLgetValue = function (queryString, connection) {
var value;
value = 0;
return connection.query(queryString, function (err, rows, fields) {
console.log("Value " + rows[0].value); //Returns correct value
return value += rows[0].value;
});
};
The console.log in the mySQLgetValue function returns the correct value from the DB. But the function call returns an Object and console.log prints "[object Object]".
What is wrong?
The console.log() is variadic, so use a comma instead of +.
console.log("Return Value", value);
The + does string concatenation, which calls the .toString() on the object, which is why you were getting [object Object].
You can't get the return value from the callback that you're passing to connection.query, because you're not the one invoking that function.
Instead, define another parameter to your function to receive a callback function that is invoked inside the callback passed to connection.query. This will replace the return statement.
app.get("/admin", function (req, res) {
var connection, value;
connection = mysql.createConnection({
host: "******",
user: "*****",
password: "****",
database: "YaAMP",
insecureAuth: true
});
var q = "SELECT property, value FROM config WHERE property = 'primeMult'";
// Pass a callback-----------------v
mySQLgetValue(q, connection, function(val) { console.log(val); });
connection.end();
return res.render("admin", {
title: "YaAMP"
});
});
// callback parameter ------------------------v
mySQLgetValue = function (queryString, connection, callback) {
var value;
value = 0;
return connection.query(queryString, function (err, rows, fields) {
console.log("Value " + rows[0].value);
// Invoke your callback
callback(value += rows[0].value);
});
};