Saturday 29 April 2017

Is opening a new connection for each query with a MongoDB database good practise?

I'm creating a web server that stores a user's data in a MongoDB database. The code behind the web requests uses asynchronous functions to insert a document into the database, but because these functions are asynchronous it means that for every request a new connection is made with the server.

exports.create_user = function(username, password, callback) {
  mongo.connect(url, function(err, db) {
    db.collection('users').insertOne({username: username, password: password}, function(err, result) {
      callback(result)
      db.close()
    })
  })
}

I'm under the impression that doing it this way is not the best practise, but I can't think a way to do it using the module model that I'm using above. Any suggestions or advice would be appreciated.



via Carl Upchurch

No comments:

Post a Comment