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.

Leave a Reply

Your email address will not be published. Required fields are marked *