Finishing up your Mongo/Node API!

You’ve created your Node API, gave it some basic functionality and now you’re going to add the ability to Update and Delete records in your MongoDB collection.

Adding the Update functionality to your Node API

An Update request is handled via the HTTP method PUT and is typically passed some data with an id to update a document in your collection. Depending on how sensitive the collection is, you would want to add validation to prevent users from updating records by passing in random ids.

	server.route({
		method: 'PUT',
		path:'/locations',
		handler: function (request, reply) {
			var locationId = request.payload.id;

			Location.findByIdAndUpdate(locationId, request.payload, function(err, location) {
				if (err) {
					return reply(err);
				} else {
					return reply(location);
				}
			});
		}
	});

Adding the Delete functionality to your Node API

Similar to Update, the Delete functionality is given an id to a document or some data to retrieve a document.

	server.route({
		method: 'DELETE',
		path:'/locations',
		handler: function (request, reply) {
			var locationId = request.payload.id;

			Location.findByIdAndDelete(locationId, function(err, location) {
				if (err) {
					return reply(err);
				} else {
					return reply(location);
				}
			});
		}
	});

In summary, your Node API should now be capable of doing the following when using the corresponding HTTP methods

  • POST – Create a document / Requires a payload containing document data
  • PUT – Update a document / Requires a payload containing document id and document data
  • GET – Get document list / No payload required
  • DELETE – Delete a document / Required a payload containing document id

With these two methods added, you have a Node API that can handle just about everything required from an API! To extend this functionality to other collections, you could simply copy/paste and substitute the collection name as needed. While that would certainly work, it wouldn’t be best practice.

Next we will focus on making sure your API is laid out in a manner that is easy to read, add functionality, test, etc.

Leave a Reply

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