arozwalak
1/23/2016 - 8:55 PM

MongoDB: Node.js Driver template

MongoDB: Node.js Driver template

var MongoClient = require('mongodb').MongoClient,
    assert = require('assert');
    
MongoClient.connect('mongodb://localhost:27017/dbname', function(err, db) {
  
  assert.equal(err, null);
  console.log("Successfully connected to MongoDB.");
  
  var query = {"field": "value"};
  var projection = {"name": 1, "category_code": 1, "_id": 0 };
  
  var cursor = db.collection('collectionname').find(query);
  cursor.project(projection);
  // or
  // var cursor = db.collection('collectionname').find(query, projection);
  
  cursor.forEach(
    function (doc) {
      console.log(doc);
    },
    function (err) {
      assert.equal(err, null);
      return db.close();
    }
  );
});