Im working on a register system and i want to check the users username if it already exists in the database while he is typing, so for every letter he types in the input field, i want to do a query to the database.
Currently I have this: on app.js i have this part of the code:
var mysql=require('mysql');
var connection=mysql.createConnection({
host:'localhost',
user:'user',
password:'password',
database:'random_name'
});
connection.connect();
app.use(function(req,res,next){
req.connection = connection;
next();
});
module.exports = app;
So far I understand this: Whenever a user requests a page, we connect to the server. But do we open a new connection or do we use the same one as before???
Then on the html page i send a request to index.js everytime the user types something into the input field and i do the following on index.js:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
var val=req.query.parameter;
var query=req.connection.query("select * from registeredusers where username="+req.connection.escape(val),function(err,result){
console.log(query.sql);
});
Am I using the same connection here when querying to the database or am I establishing a new connection whenever a user types something into the input field?
EDIT: The connection wasnt persisted, i followed the advice of Mjh, so the sollution for this problem is using pooling connections.Check this links out if you want to know more: When use poolConnection or CreateConnection felixge/node-mysql