jia chen jia chen - 1 year ago 81
Node.js Question

Structuring database code in NodeJS

Im a java programmer who just started javascript.

I created a mongo database on mlabs and now im writing the code to connect to the database.

How are database code structured in node, is there a way to connect to the db in a non blocking way?

Answer Source

Mongodb's official driver connects to the db asyncronously with a callback.

from the README:

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected correctly to server");


Say you wanted to send the results of a find() as a response in json format, you would:

  • Connect the the db.
  • inside the connect callback, call a db.collection.find()
  • inside the find() callback, pass the results to a response send handler. (res object in an express get() ).

So the pattern is:nesting the callbacks and terminate with a call to your response object/MVC controller/something similar.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download