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:
npm install --save mongoose
We also need to install the body-parser, which parses JSON bodies for Express.
npm install --save body-parser
Next, copy all of this to your main.js file:
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); //mongoose uses Schema as a layer on a MongoDb document (which represents a model): var Schema = mongoose.Schema; app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); //connect to mongodb: mongoose.connect('mongodb://localhost:27017/restaurant'); //create a Schema for our food: var FoodSchema = new Schema({ name: { type: String, index: { unique: true } }, description: String, price: String }); // Use the schema to register a model with MongoDb mongoose.model('Food', FoodSchema); var food = mongoose.model('Food'); //POST verb app.post('/food', function (req, res) { food.create(req.body, function (err, food) { if (err) { res.send(401, err); return; } res.send(req.body); }); }); //GET verb app.get('/food', function (req, res) { food.find(function (err, data) { if (err) { res.send(err); } res.json(data); }); }); //GET/id app.get('/food/:id', function (req, res) { food.findOne({ _id: req.params.id }, function (error, response) { if (error) { res.send(error); } else { res.send(response); } }); }); //GET by name app.get('/foodname/:name', function (req, res) { food.findOne({ name: req.params.name }, function (error, response) { if (error || !response) { res.send("not on the menu"); } else { res.send(response); } }); }); app.set('port', process.env.PORT || 3000); app.listen(app.get('port')); console.log("the server is running on http://localhost:" + app.get('port'));
Now run it with the following command:
nodemon main.js
What happened?
Let's dissect the code from the previous paragraph:
1.
We added and instantiated the prerequisites and connected to our MongodB instance
var bodyParser = require('body-parser'); var mongoose = require('mongoose'); //mongoose uses Schema as a layer on a MongoDb document (which represents a model): var Schema = mongoose.Schema; app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); //connect to mongodb: mongoose.connect('mongodb://localhost:27017/restaurant');
2.
We create a Schema for our Food class:
//create a Schema for our food: var FoodSchema = new Schema({ name: { type: String, index: { unique: true } }, description: String, price: String }); 3. Then we used the schema to register a model with MongoDbmongoose.model('Food', FoodSchema); var food = mongoose.model('Food');4.
And then we are ready to define our CRUD methods, e.g.//POST verb app.post('/food', function (req, res) { food.create(req.body, function (err, food) { if (err) { res.send(401, err); return; } res.send(req.body); }); }); //GET verb app.get('/food', function (req, res) { food.find(function (err, data) { if (err) { res.send(err); } res.json(data); }); });Using the API with Curl
You can add a menu item with the following command:
curl -H "Content-Type: application/json" -d '{ "name": "papadums", "description" : "Thin Bread", "price" : "2.00" }' http://localhost:3000/foodIssue a get:
curl http://localhost:3000/food
3 thoughts on “Beginning Node.js – REST API with a Mongodb backend – part 3”