I want to get "information" in this case but have to be necessarily outside of the funtion
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'db_name'
});
connection.connect();
var insert = {
information : something
};
var query = connection.query('insert into db.table set ?', insert, function (err, result) {
if (err) {
console.error(err);
return;
}
else {
**getInformation = results;**
}
console.error(result);
});
connection.end();
I'm trying but doesn't work
console.log(getInformation)
You are calling conneciton.end() before the callback gets invoked.
Try the following:
connection.connect();
var insert = { information : 'something' };
var query = connection.query('insert into db.table set ?', insert, function (err, result) {
if (err) {
console.error(err);
return;
}
console.log(result);
connection.end();
});
Related
I want to get my collection data, my collection is named students and is part of my pool database.
The connection to the mongoDB works, however console.log(result.lastname) returns undefined.
Here is my server.js file
var mongo = require('mongodb');
var assert = require('assert');
const url = 'mongodb://localhost:27017/';
mongo.connect(url, function (err, db) {
if(err) {
console.log("Connection failed");
}
console.log("Connection successfull");
var dbo = db.db("pool");
dbo.collection("students").find({}, function(err, result) {
if (err) throw err;
console.log(result.lastname);
db.close();
});
});
And the content in my students collection that I see using db.students.find(); directly in console
{ "_id" : ObjectId("5eb1570f2c0167c90cc127fd"), "id" : 0, "lastname" : "Sam", "firstname" : "Sung", "email" : "sc#mail.com", "phone" : 613295990, "validated" : "Validated", "admin" : true }
According to this link:
https://docs.mongodb.com/manual/reference/method/db.collection.find/
.find() returns a list and not just one entry. Meaning even though your collection has one entry, it will be received as a list with just one entry.
You have to iterate.
So, try this:
var mongo = require('mongodb');
var assert = require('assert');
const url = 'mongodb://localhost:27017/';
mongo.connect(url, function (err, db) {
if(err) {
console.log("Connection failed");
}
console.log("Connection successfull");
var dbo = db.db("pool");
dbo.collection("students").find({}, function(err, result).toArray(function(err, result) {
if (err) throw err;
console.log(result.lastname);
db.close();
});
});
Another helpful link : https://www.w3schools.com/nodejs/nodejs_mongodb_find.asp
I think it is returning an array, can you try:
result[0].lastname
I am getting an error on node.js, and I cannot identify why. Can anybody help me? If I add only 1 data from the array it gets added to the database. However, when I add other inputs, it displays an error in node.js and doesn't get saved in my database.
var express = require('express');
var app = express();
app.get('/register/*', handleGetRequest); //how do I pass usrName here?
app.use(express.static('public'));
app.listen(5000);
function handleGetRequest(request, response){
var pathArray = request.url.split("/");
var pathEnd = pathArray[pathArray.length - 1];
if(pathEnd === 'register'){
response.send("{working}");
//console.log(request.body.usrName);
}
else
var registerArray = pathEnd.split("&");
response.send(JSON.stringify(registerArray));
saveToDb(registerArray);
// response.send("{error: 'Path not recognized'}");
}
function saveToDb(registerArray){
for (var i = 0; i < registerArray.length; i++) {
console.log(registerArray[i]);
}
var mysql = require('mysql');
var con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'customer',
port: 6000
});
con.connect();
addData();
function addData(){
var query = con.query(
"INSERT INTO cust (id,LastName,FirstName) VALUES
('001,"+registerArray[0]+"," +registerArray[1]+"');",function(err, result,
fields){
if (err) throw err;
console.log('results' , result);
}
);
}
//Close the connection
con.end();
}
You are missing single quotes in your SQL statement that cause the problem. The code should look like this:
function addData(){
var query = con.query(
"INSERT INTO cust (id,LastName,FirstName) VALUES
('001','"+registerArray[0]+"','" +registerArray[1]+"');",
function(err, result, fields) {
if (err) throw err;
console.log('results' , result);
}
);
}
This is in a mysql.js file:
const mysql = require('mysql');
const config = require('./config.json');
const con = mysql.createConnection({
host: config.dbhost,
user: config.dbuser,
password: config.dbpass,
database: config.dbname,
});
module.exports = {
findUser: function(email) {
const sql = 'SELECT * FROM users WHERE email = ' + mysql.escape(email);
con.connect(function(err) {
if (err) throw err;
console.log('Connected!');
con.query(sql, function(err, result) {
if (err) throw err;
return result[0].id;
});
});
},
};
then within my index.js file there is this:
const mysql = require('./mysql.js');
console.log(mysql.findUser('example#example.test'));
When the code is running, it outputs "undefined" and then "Connected!" after the db connection is made. Even though if I do a console.log on result[0].id it outputs 1, which is the correct id...
Question: How can I load the mysql.js file first before the function is called?
You need to wait for response cause its an asynchronous function.
Try using callback or promises.
Callback example:
mysql.findUser('example#example.test', function(res)){ console.log(res)});
module.exports = {
findUser: function(email, callback) {
const sql = 'SELECT * FROM users WHERE email = ' + mysql.escape(email);
con.connect(function(err) {
if (err) throw err;
console.log('Connected!');
con.query(sql, function(err, result) {
if (err) throw err;
callback(result[0].id);
});
});
},
I am still new to nodejs and Javascript, I am sorry if my question appear to be very simple but I am struggling a lot and I can't seem to find an answer on the net.
What I want to do is basically calling a script (sqlRequest.js) and send an integer while calling it. This script will send an sql request to my database and will return the result (an object) to the original file.
Here are the codes:
router.post('/request', function(req, res, next){
var id = req.body.id;
var essai = require('./sqlRequest.js');
console.log("INDEX: "+essai.sendSQL(id)); });
And now the sqlRequest.js code:
exports.sendSQL = function(id) {
var mysql= require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'bcombes',
password : 'bertrand1994',
database : 'totalkpi'
});
connection.connect();
var sql ="SELECT * FROM tra_ticket where id=?";
var insert=[id];
sql=mysql.format(sql, insert);
connection.query(sql, function(err, rows, fields) {
if (err) {
console.log('Error while performing Query.');
connection.end();
}
else {
connection.end();
console.log(rows);
return rows;
}
});};
On the console I can see that the console.log("INDEX: "+essai.sendSQL(id)); appears to be undefined and is displayed before the console.log(rows).
Is it possible that the server does not wait for the function to finish and display the variable anyway ?
Anyway thank you for taking the time to help.
Your logic to pass a variable between files is fine. The reason your seeing essai.sendSQL(id) return undefined is because connection.query(...) is called asynchronously and, as you've mentioned in your question, the console.log fires before the DB query completes.
To fix that issue you just need to refactor your code slightly:
var essai = require('./sqlRequest.js');
router.post('/request', function(req, res, next){
var id = req.body.id;
// send callback to sendSQL
essai.sendSQL(id, function(index) {
// this will only fire once the callback has been called
console.log("INDEX: " + index)
})
});
And then in sqlRequest.js:
exports.sendSQL = function (id, cb) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'bcombes',
password: 'bertrand1994',
database: 'totalkpi'
});
connection.connect();
var sql = "SELECT * FROM tra_ticket where id=?";
var insert = [id];
sql = mysql.format(sql, insert);
connection.query(sql, function (err, rows, fields) {
if (err) {
console.log('Error while performing Query.');
connection.end();
}
else {
connection.end();
console.log(rows);
// call the callback
cb(rows);
}
});
};
Both .js files are in the same folder. And I'm attempting to run the app, but I recieve that connection is not defined in user.js. It's on the row where query is called on connection that it says that it's not defined.
index.js
var exports = module.exports = {};
var user = require('./user');
exports.User = user;
exports.startCon = startCon;
var mysql = require('mysql2');
function startCon() {
return mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'users'
})
}
user.js
var dal = require('./index');
function User(){
this.connection = null;
}
User.prototype.getAll = function(cb){
this.connection = dal.startCon();
connection.query('SELECT * FROM user;', function (error, data) {
if(!error){
cb(null, data);
}
else {
console.log("Error Selecting : %s ", error );
cb(error);
}
});
connection.end();
}
module.exports = User;
Try close connection inside the callback function
callback() {
connection.close()
}
And this module really weird
You need construct connection instance inside function
var mysql = require('mysql');
let doSmth = function(userId) {
let connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'test'
});
return new Promise((resolve, reject) => {
connection.query({
sql: 'SELECT `address` FROM `User` WHERE `user_id` = ?'
},
[userId],
function (error, results, fields) {
console.log(error, results)
if(!error) {
var obj = JSON.parse(JSON.stringify(results));
resolve(obj)
} else {
reject(error)
}
}
);
})
}
module.exports = {
doSmth
};