MongoDB (with Node.js)

We recommend using MongoDB as a backend to your node application - MongoDB is lightweight and easy to use, especially if you're a beginner. For node, there is a easy to use module to interface with your Mongo database - mongoose (http://mongoosejs.com/).

To install Mongo on your laptop and make sure that Mongo is running. The command to start mongo is

mongod
Download MongoDB here: https://www.mongodb.org/downloads

Using MongoDB

To connect to the database, there are three parts:

  1. Connecting to the database

    Connecting to the database is pretty simple - you can replace test with whatever database name you want - if it doesn't exist, mongoose will automatically create one for you. Be sure to replace test in both the connect and the on disconnect methods below:

    // DATABASE CONNECTION
    mongoose.connect('mongodb://localhost/test');
    
    // Error handler
    mongoose.connection.on('error', function (err) {
      console.log(err)
    });
    
    // Reconnect when closed
    mongoose.connection.on('disconnected', function () {
      mongoose.connect('mongodb://localhost/test');
    });
    
    
  2. Creating a Schema

    Databases consists of models, which are described by schemas, which is like a set of instructions for what your data should look like. For example:

    var SampleModel = require('../models/sample')(mongoose);
    What this line says is it's looking in the /models/ folder for a file called sample.js. This file is the one that actually holds the schema and returns the corresponding Model object, which you will use from then on to create new objects, query your database, etc etc.
    
    Looking in /models/sample.js, you'll see
    
    var Schema = mongoose.Schema
    
    var sampleSchema = new Schema({
      text: String
    });
    
    return mongoose.model('Sample', sampleSchema);
    

    This code simply says create a new Schema with just a single text field called 'text', and then return a model with that schema called 'Sample'. Any models created with the Sample model will have a text field to go with it. If you want to create new models, just create a new file in the /models/ folder called yourmodel.js, copy the contents of sample.js, and change the names and fields according to what your new model is. Then in routes/routes.js you will want to load your model with the code:

    var YourModel = require('../models/yourmodel.js')(mongoose);
    
  3. Using the Model

    To actually save something to the database:

    var example = new SampleModel({text: "This is a test."});
    example.save(function(err) {
      if (err) {
        // do something with error
      } else {
        // do something on success
      }
    });
    

More Mongo!

For more information on how to use Mongo/Mongoose, you can visit their docs at http://mongoosejs.com/docs/guide.html