Sep 4, 2012

MongoDb + NodeJs = Easy!

I'm just starting at rewriting my Jobagator.org Rails app using ember + node + mongodb. Wow was it is easy to get started with the server-side:

var mongodb = require('mongodb');
var Db      = mongodb.Db;
var Server  = mongodb.Server;

var client = new Db('jobagator', new Server("127.0.0.1", 27017, {}));

client.open(function(err, p_client) {
  client.collection('post', function(err, posts) {
    posts.count(function(err, count) {
      console.log("#posts = "+count);
    });
  });
});
Edit: Weaving express into the mix wasn't hard either:
var mongodb = require('mongodb');
var express = require('express');
var http = require('http');
var path = require('path');

var Db      = mongodb.Db;
var Server  = mongodb.Server;

var app = express();
var server = http.createServer(app);

server.listen(process.env.PORT || 8080);

var publicpath = path.normalize( __dirname + "/../public");
app.use(express.static(publicpath));

var client = new Db('jobagator', new Server("127.0.0.1", 27017, {}));

// Is this dangerous?
client.open(function(err, p_client) { });

app.get('/posts', function(req, res){
  client.collection('post', function(err, collection) {
    collection.find().toArray(function(err, results) {
      res.send(JSON.stringify(results));
    });
  });
});

No comments: