Expand your Mongo/Node API in 10 more minutes!

Previously we spent 10 minutes setting up a barebones Node API using Mongo and Node. Now we are going to invest 10 more minutes to add Create and Read Mongo functionality. These are known as the C and R of CRUD functionality.

Begin the Node API expanding!

Install Mongoose

npm install mongoose

Mongoose is a ORM the bridge between our Node API and Mongo. Mongoose allows you to create models via Node and associate them with your Mongo collections.

Create a Model

A model is a representation of your Mongo collection. In our case, we are going to have a Locations collection consisting of a latitude, longitude, and created fields.

Your directory structure should look similar to this:

models
- Location.js
node_modules
index.js
package.json
Procfile

Create the following Location.js file in a models directory

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var LocationSchema = new Schema({
  name: { type: String, required: true },
  description: { type: String },
  lat: { type: String, required: true },
  lng: { type: String, required: true },
  created: { type: Date, required: true, default: Date.now }
});

module.exports = mongoose.model('Location', LocationSchema);

Update index.js to include new routes

Our server needs to know when to read our Locations or create a Location when you access a specific URL with a given server method. The server methods we will be working with are GET and POST.

const Hapi = require('hapi');
const Mongoose = require('mongoose');

const Location = require('./models/Location');

// Create a server with a host and port
const server = new Hapi.Server();

var mongoUri = process.env.MONGODB_URI || 'mongodb://YOUR_MONGO_URI';
var serverPort = process.env.PORT || 8080;

Mongoose.connect(mongoUri, function(err) {
	if (err) {
		console.log(err);
		process.exit(1);
	}

	server.connection({
		port: serverPort
	});

	// GET locations route
	server.route({
		method: 'GET',
		path:'/locations',
		handler: function (request, reply) {
			// Retrieve all locations
			Location.find({}, function(err, locations) {
				return reply(locations);
			});
		}
	});

	// POST locations route
	server.route({
		method: 'POST',
		path:'/locations',
		handler: function (request, reply) {
			// Make a new location
			var location = new Location();

			// Assign the new location fields to the values from our POST
			location.name = request.payload.name;
			location.description = request.payload.description;
			location.lat = request.payload.lat;
			location.lng = request.payload.lng;

			location.save(function(err, location) {
				if (err) {
					return reply(err);
				} else {
					Location.find({}, function(err, locations) {
						console.log(locations);
					});
					return reply(location);
				}
			});
		}
	});

	// Start the server
	server.start((err) => {

		if (err) {
			throw err;
		}
		console.log('Server running at:', server.info.uri);
	});
});

To explain in detail, your Node API will respond different depending on how you access it. When you to tell your Node API to GET /locations via http://yourapi:8080/locations then you should be presented with a list of Locations from your Mongo database.

When you access your Node API via a POST request to http://yourapi:8080/locations and provide it with some data, your Node API should respond by inserting provided data into your Mongo database.

That’s it! You now have the ability to retrieve and create new records. Further enhancements could be to add validation to your POST request to ensure things don’t go haywire with bogus data or even add the ability to update (via PUT) or delete (via DELETE) your records.

Create a Mongo/Node API in 10 minutes!

Using Heroku, you can get the barebones of a Node/Mongo API in just under 10 minutes!

    Prerequisites

  • A registered Heroku account
  • Install Heroku CLI
  • Access to your Heroku dashboard
  • Step 1 – Create and navigate to project directory

    Wherever you want your project to be. Perhaps c:\My Cool Things\API or /Users/hank/projects/api-project.

    Step 1 – Create Heroku app

    From the command line of your choice, from your project directory:

    $ heroku create

    You’ll be presented with a nifty server name. Something like falling-wind-1234 or similarly zen-like.

    Step 2 – Create app structure

    For a barebones API you’ll need just just 3 basic things.

    2a – Procfile
    Needed for Heroku to run the app. The contents of this file is just one line for now.

    web: node index.js

    2b – package.js
    This manages your node packages and will be managed automatically via your

    $ npm install

    commands you make later.

    Type

    $ npm init

    and hit enter through all of the prompts. The default values will be fine for now.

    2c – index.js
    The starting point of your app will start and connect to your mongo/node server. We will create this in Step 4!

    Step 3 – Install dependencies

    Since this is a barebone API, we will have just 3 dependencies: mongodb and hapijs

    Back at the command line, type

    $ npm install mongodb --save
    $ npm install hapijs --save
    $ npm install mongoose --save

    Step 4 – Create index.js

    const Hapi = require('hapi');
    const Mongoose = require('mongoose');
    
    // Create a server with a host and port
    const server = new Hapi.Server();
    
    var mongoUri = process.env.MONGODB_URI || 'mongodb://YOUR_MONGO_URI';
    var serverPort = process.env.PORT || 8080;
    
    Mongoose.connect(mongoUri, function(err) {
    	if (err) {
    		console.log(err);
    		process.exit(1);
    	}
    
    	server.connection({
    		port: serverPort
    	});
    
    	// GET locations route
    	server.route({
    		method: 'GET',
    		path:'/hello',
    		handler: function (request, reply) {
    			return reply("Hello, this is my API");
    		}
    	});
    
    	// Start the server
    	server.start((err) => {
    
    		if (err) {
    			throw err;
    		}
    		console.log('Server running at:', server.info.uri);
    	});
    });
    
    

    Step 5 – Deploy!

    To send it up to your Heroku app, type

    $ git commit -am "My 10 minute API!"
    $ git push heroku

    After the app is built, you can navigate to your Heroku app url (for example, https://guarded-bear-24888.herokuapp.com/) and see the results!

    Using our example, navigating to just the base url will produce a 404, but a valid response nonetheless! If you navigate to the base url followed by /hello, you should get our hello world response.

    Next steps for your newly minted API could be to create some routes that interact with your mongo instance, make some hapijs views or publish your code to your personal github repo.