Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8426681
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T04:35:46+00:00 2026-06-10T04:35:46+00:00

main.js var http = require(‘http’); var UserModel = require(‘./models/user.js’); var server = http.createServer(function(req, res){

  • 0

main.js

var http = require('http');
var UserModel = require('./models/user.js');
var server = http.createServer(function(req, res){
  UserModel.create({
  }), function(e, o){
    if(e) { console.log(e); } else {
    } console.log(o); }
  });
}).listen(3000);

connections.js

var mongo = require('mongodb');

module.exports = {
    dbMain: new mongo.Db('main', new mongo.Server('127.0.0.1', 27017, { auto_reconnect: true }, {})),
    dbLog: new mongo.Db('log', new mongo.Server('127.0.0.1', 27017, { auto_reconnect: true }, {}))
};

/models/user.js

var mongodb = require('mongodb');
var db = require('./connections.js').dbMain;

module.exports = {
  create: function(newData, callback){
    db.open(function(e, db){
      db.collection('users', function(e, collection){
        collection.insert(newData, callback);
      });
    });
  }
}

When I use the code above, the server crashes with the problem that, the SECOND time a request comes in, we still have the database connection opened, so lets add db.close to our Users.create function.

  create: function(newData, callback){
    db.open(function(e, db){
      db.collection('users', function(e, collection){
        collection.insert(newData, function(e, o){
          db.close(); // Voila.
          callback(e, o);
        });
      });
    });
  }

At this stage the server CAN still crash, because of multiple connections open, I don’t understand why or how this can happen but it does.

How do I organize my project into models (I don’t want to use Mongoose, my validation is done in a different layer not the model, so Mongoose would be an overkill for me)? Also how do I handle connections in the project?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T04:35:47+00:00Added an answer on June 10, 2026 at 4:35 am

    you could have a library that wraps all this up nicely – it means that only one connection to the database will be opened and the same (open) connection will be returned for the second request – if you are getting 1000+ per second, this is a make-or-break issue (i.e. not re-opening the connection each request)…

    users.js:

    var connections = require('./connections.js');
    
    var serverCache = connections('127.0.0.1', 27017); 
    
    module.exports = {
      create: function(newData, callback){
        serverCache('main', 'users', function(e, collection){
          collection.insert(newData, callback);
        })
      }
    }
    

    connections.js

    var mongo = require('mongodb');
    
    // a mongo connection cache
    // pass in host & port
    // it returns a function accepting dbName, collectionName & callback
    var mongoCache = function(host, port){
    
      // keep our open connections
      var mongoDatabases = {};
    
      var ensureDatabase = function(dbName, readyCallback){
        // check if we already have this db connection open
        if(mongoDatabases[dbName]){
          readyCallback(null, mongoDatabases[dbName]);
          return;
        }
    
        // get the connection
        var server = new mongo.Server(host, port, {auto_reconnect: true});
    
        // get a handle on the database
        var db = new mongo.Db(dbName, server);
        db.open(function(error, databaseConnection){
          if(error) throw error;
    
          // add the database to the cache
          mongoDatabases[dbName] = databaseConnection;
    
          // remove the database from the cache if it closes
          databaseConnection.on('close', function(){
            delete(mongoDatabases[dbName]);
          })
    
          // return the database connection
          readyCallback(error, databaseConnection);
        })
      }
    
      var ensureCollection = function(dbName, collectionName, readyCallback){
    
        ensureDatabase(dbName, function(error, databaseConnection){
          if(error) throw error;
    
          databaseConnection.createCollection(collectionName, function(error, collection) {
            if(error) throw error;
    
            // return the collection finally
            readyCallback(error, collection);
          })
    
        })
      }
    
      return ensureCollection;
    }
    
    module.exports = mongoCache;
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Jsfiddle: http://jsfiddle.net/yJJs7/ Javascript: function main(){ var centerx=250; var centery=250; var degrees=0; var div=document.getElementById('test'); var
I create a document class Main and use Adobe Sample code from http://help.adobe.com/en_US/as3/components/WS5b3ccc516d4fbf351e63e3d118a9c65b32-7f9f.html and
I have the following code in server/statusboard.js; var require = __meteor_bootstrap__.require, request = require(request)
For example, static void Main() { var someVar = 3; Console.Write(GetVariableName(someVar)); } The output
var main = (from d in db.Discounts where d.Id == discount.Id && d.UserId ==
int main() { int var = 0;; // Typo which compiles just fine }
class OneAtATimePlease { static void Main() { using (var mutex = new Mutex(false, oreilly.com
First look at this code: class Program { static void Main(string[] args) { var
I've got really simple code: static void Main(string[] args) { var task = Task.Factory.StartNew(GetInt);
I build some validation service. private static void Main(string[] args) { var service =

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.