Beginning Node.js – REST API with a Mongodb backend – part 3

This is the sequel to this article. I’m building a REST API from the ground up with Node.js and Express.js 4. I’m adding functionality as I go. I’m starting with Node.js, then I’m adding Express and now I’m adding Mongoose. In the next articles I will be adding Passport.js for authentication and start building a frontend, either with Angular of Ember.

Things have changed slightly since my former series, see here. That’s because Express.js version 3 has evolved to version 4. The main difference between version 3 and 4 is that version 3 contains middleware (JSON parsers, session support and so on). In version 4 you need to add the middleware yourself. That means installing body-parser, session and so on with NPM.

In my former article we used a JSON string with data. Now let’s use a real data backend: MongoDb. Mongoose is an ORM for MongoDb for Node.js, so let’s add the module to the project:

We also need to install the body-parser, which parses JSON bodies for Express.

Next, copy all of this to your main.js file:

Now run it with the following command:

What happened?

Let’s dissect the code from the previous paragraph:

We added and instantiated the prerequisites and connected to our MongodB instance

We create a Schema for our Food class:

And then we are ready to define our CRUD methods, e.g.

Using the API with Curl

You can add a menu item with the following command:

Issue a get: