I am having a few issues with one route that I am looking at...
app.get('/newusersvariables', function(req, res) {
const sessionid = req.session.id;
//let newuser = mysql.createConnection(mysqlconfig);
let connection = mysql.createConnection(mysqlconfig);
connection.connect(function(err) {
if (err) throw err;
connection.query("SELECT * FROM user_idpdetails WHERE sessionid = ?", [sessionid], function (err, result, fields) {
if (err) throw err;
console.log(result);
connection.end();
});
});
I have tried moving around the connection.end but to no avail. In some situations, I get connection lost, as if it is ignoring the connection end. And if I move it to other places then I am getting
'Error: Cannot enqueue Query after invoking quit.'
It is most likely something simple that I am overlooking as I am new to node.
Related
I have 2 URLs, one points to a different connection string and the other to local MongoDB instance. While I establish the connection to MongoDB using MongoClient with url1 and fetch the required data from a DB/collection and lastly store it in an array.
Now I want to insert this array to a localhost MongoDB collection and on doing so I get MongoError: Topology is closed, please connect error.
app.js
var url1="someurl but not localhost";
var url2="mongodb://localhost:27017/";
router.get('/route1', function(req, res)
{
MongoClient.connect(url1,{ useUnifiedTopology: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("customer");
dbo.collection("customer_report").find({}).toArray(function(err, result) {
if (err!=null){
console.log("Connection Failed!!"+err)
}
var customerArray =[];
for(i=0;i<result.length;i++){
backupArray.push({
a: result[i].a,
b: result[i].b,
c: result[i].c,
d: result[i].d,
});
}
console.log(customerArray);
res.json({content:customerArray});
db.close();
MongoClient.connect(url2,{ useUnifiedTopology: true }, function(err, db1) {
//Trying to establish another mongodb connection wuth new url
if (err) throw err;
var dbo = db.db("localdb");
dbo.collection("localcollection").insertMany(customerArray, function(err, res) {
if (err) throw err;
console.log("Number of documents inserted: " + res.insertedCount);
db1.close();
});
});
});
});
});
And if I don't close db.close(); then the array data gets appended to first MongoDB collection and not the local MongoDB. Looking for a solution to handle two MongoClient at the same time or a way to insert the customerArray to local MongoDB collection.
Is there a workaround where I can add the array elements to my local MongoDB collection?
In your second mongo connect block I think you want
var dbo = db.db("localdb");
to be
var dbo = db1.db("localdb");
Have you made sure those credentials work in console commands? And have you made sure the last connection through the console is closed before trying to use them in the script?
I have a web server run by node.js
It uses Express, Socket.io, and MySQL
I use socket.io to transmit data from client to server, and also to call queries.
After implementing SQL connexion and queries, the server started to stop after exactly 60 seconds running it.
SQL part in the index.js file:
// SQL
var mysql = require('mysql');
var con = mysql.createConnection({
host: "...",
user: "...",
password: "...",
database: "..."
});
//Socket.io
var io = require('socket.io') (serv, {});
io.sockets.on('connection', function(socket) {
// Select
socket.on("recherche", function(data) {
if (err) throw err;
con.query("SELECT * FROM ..", function (err, result, fields) {
if (err) throw err;
socket.emit("...", {data: result});
});
});
// Insert into
socket.on("...", function(data) {
con.connect(function(err) {
if (err) throw err;
var sql = "INSERT INTO ... VALUES (...)";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
});
});
Everything is working just fine for 60 second after start the server.
Then, I have this error message in the nodejs console:
C:\Users\...>node index.js
events.js:187
throw er; // Unhandled 'error' event
^
...
Error: Connection lost: The server closed the connection.
...
fatal: true,
code: 'PROTOCOL_CONNECTION_LOST'
Thank you in advance to read my question :D
connection = mysql.createConnection(db_config); // Recreate the connection, since
connection.connect(function(err) {
if(err) {
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000);
}
});
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleDisconnect();
} else {
throw err;
}
});
I am trying to make a REST api in node using express. When i open the url in browser the first time, it runs fine and gives me the correct output. But when I hit the api url the second time, the app crashes with the error :
events.js:141
throw er; // Unhandled 'error' event
^
Error: Cannot enqueue Handshake after invoking quit.
This is the code I'm using :
var express = require('express');
var mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: 'USER_NAME',
password: 'PASSWORD'
});
app.use(express.static(__dirname + '/public'));
var port = 3333;
app.get('/api/users/:user_id', function(req, res){
var lead_id = req.params.user_id;
connection.connect();
connection.query('use DB_NAME;', function (err) {
if(err) throw err;
connection.query('select * from users where user_id = ' + user_id, function (err, rows) {
if(err) throw err;
res.json(rows);
connection.end();
});
});
});
app.listen(port);
console.log("The app is running on port " + port);
Can someone tell me what am I doing wrong ?
Just remove connection.connect() and connection.end(). Then it should work.
connection.connect() should be called once or none. Because connection.query will connect I'd it not connected.
PS - connection.connect() need to be called when the connection is lost.
Try this to remove the redudant connection. This was the first result of a google search of the error message - always try to google error messages before asking SO.
Hi I am currently trying to output mysql data to a browser window instead of the console, and I have not a clue on how to do this in Node, which I am quite new to.
Here is the mysql.js file:
'
var mysql = require ("mysql");
var connection = mysql.createConnection({
host:"localhost",
user: "root",
});
connection.connect(function (err) {console.log( "Successfully Connected.");
if (err) throw err;
});
var query = connection.query("SELECT * FROM myTable", function (err, result, fields){
if (err) throw err;
console.log('result:', result);
});
connection.end();'
You need to create a server which you can connect to and receive data from with a browser. The most convenient and by far the simplest way to do this is HTTP. You can read about HTTP servers in node.js here. The fist code snippet on that page demonstrates a HTTP server with one handler function, which is all you need to achieve your goal.
An (untested) example for convenience:
// Dependencies
var mysql = require("mysql"),
http = require("http");
// This holds our query results
var results;
// Connect to database
var connection = mysql.createConnection({
host: "localhost",
user: "root"
});
connection.connect(function(err) {
if (err) throw err;
console.log("Connected to database");
});
connection.query("SELECT * FROM myTable", function(err, rows, fields) {
if (err) throw err;
results = rows;
connection.end(); // Disconnect from database
});
// Function to handle browser's requests
function requestHandler(req, res) {
res.end(JSON.stringify(results)); // Respond to request with a string
}
// Create a server
var server = http.createServer(requestHandler);
// That magic number 8080 over here is the port our server listens to.
// You can access this webpage by visiting address http://localhost:8080
server.listen(8080, function() {
console.log("Server online");
});
Let's imagine we have Node.JS app which is connecting to the Mongos process. But suddenly Mongos failed. How our app could now about it?
var db = null;
mongo.MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, mydb) {
if(err) throw err;
db = mydb
});
..... on response we have .....
db.collection('test_collection', function(err, collection){
collection.find({}).toArray(function(err, documents){
// doing some work here
// but if Mongos failed, we are blocked on this stage
});
});
Would you not want to do the same thing that you're doing at connect, but within the function?
i.e.
...
collection.find({}).toArray(function(err, documents) {
if(err) {
throw err; //or do something equivalent. It doesn't really matter if the connection has failed, as it will still throw an error.
} else {
///continue processing
}
....
Alternatively, if you use a 3rd party mongo manager, such as mongoose, you can do something like this globally:
mongoose.connect('mongodb://' + config.mongo.host + '/' + config.mongo.db);
var db = mongo.connection;
db.on('error', console.error.bind(console, 'connection error: '));