MongoDB and Node.js example

The following code provides a brief reference example of reading data from a MongoDB database using Node.js. 


The following is already in place:

  • I've created a database in MongoDB called beetleJuice
  • Within the beetleJuice database, I've created a collection called bugs
  • The mongo dependency has been saved to the project directory
  • I have an instance of MongoDB running on port 27017
// Bring in the MongoDB dependency

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

// Connect to the database

MongoClient.connect('mongodb://localhost:27017/beetleJuice', function (err, db) {
    assert.equal(null, err);
    // assign the bugs collection to var col
    var col = db.collection('bugs');
    // use the findOne method to search for a document where assignee is set to Daniel Hoadley
    col.findOne({"assignee" : "Daniel Hoadley"}, function (err, doc) {
        assert.equal(null, err);
    // Print the resulting document to the console
        console.log("Here is my doc: %j", doc);
    // Close the connection to the database

Convert JSON to CSV with plain Javascript

I've been exploring the excellent API provided by the Canadian case law database, CanLII, and needed to quickly convert the JSON I was puling back to CSV. 

The following code, which has been tailored to suit the structure of the data coming back from the API, got the job done:

// Include dependencies

var json2csv = require('json2csv');
var fs = require('fs');

// Set up columns in the CSV
var fields = ['databaseId', 'caseId.en', 'title', 'citation'];

// Give it the data

var cases = [
        "databaseId": "csc-scc",
        "caseId": {
        "en": "2016scc56"
        "title": "Canada (Attorney General) v. Fairmont Hotels Inc.",
        "citation": "2016 SCC 56 (CanLII)"
        "databaseId": "csc-scc",
        "caseId": {
        "en": "2016scc55"
        "title": "Jean Coutu Group (PJC) Inc. v. Canada (Attorney General)",
        "citation": "2016 SCC 55 (CanLII)"

var csv = json2csv({ data: cases, fields: fields });

fs.writeFile('cases.csv', csv, function(err) {
    if (err) throw err;
        console.log('Case list converted and saved as CSV!!');