Cristian Toma
Cristian Toma

Reputation: 5799

NodeJS: Where to connect to the database in code?

I have a simple express server running on NodeJS and I want to perform database queries when receiving requests. My setup looks similar to this

var srv = require('express').createServer();
var db = new DbConnection(dsn);

srv.get('/', function (req, res) {
    var result = db.query(query);

    res.send(result);
});

srv.listen(80);

Will I have problems with concurrency ? What if two requests are being handled simultaneously and thus the querying is done simultaneously ?

I also thought about this approach

srv.get('/', function (req, res) {
    var db = new DbConnection(dsn);

    var result = db.query(query);

    res.send(result);
});

What do you thing is the best approach/practice to do this ?

Upvotes: 2

Views: 2570

Answers (1)

generalhenry
generalhenry

Reputation: 17319

The key to node.js performance is to never block the thread.

var result = db.query(query);

is a big no no.

db.query(query, function(result) {
  res.send(result);
});

is the way queries for requests should be handled

connecting once should be fine, most databases have no issues with queues.

Upvotes: 6

Related Questions