Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
MongoDB, Express, Angular, and Node.js Fundamentals

You're reading from   MongoDB, Express, Angular, and Node.js Fundamentals Become a MEAN master and rule the world of web applications

Arrow left icon
Product type Paperback
Published in Mar 2019
Publisher
ISBN-13 9781789808735
Length 362 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Paul Oluyege Paul Oluyege
Author Profile Icon Paul Oluyege
Paul Oluyege
Arrow right icon
View More author details
Toc

Table of Contents (9) Chapters Close

MongoDB, Express, Angular, and Node.js Fundamentals
Preface
1. Introduction to the MEAN Stack FREE CHAPTER 2. Developing RESTful APIs to Perform CRUD Operations 3. Beginning Frontend Development with Angular CLI 4. The MEAN Stack Security 5. Angular Declarables, Bootstrapping, and Modularity 6. Testing and Optimizing Angular Applications Appendix

Chapter 2: Developing RESTful APIs to Perform CRUD Operations


Activity 3: Connecting the Node application with MongoDB Atlas

  1. Create a subfolder named config and create a db.js file inside config folder.

    First, open server folder in the Blogging Application folder by using the keyboard combination Ctrl + O or Ctrl + k from Visual Studio Code and enable the integrated terminal with Ctrl + '. To accept default npm commands, create a package.json file using the following code:

    npm init
  2. Install mongoose and import Mongoose.

    To install and import Mongoose, first open the db.js and type the following:

    npm install mongoose -- save

    To import Mongoose, type the following code:

    const mongoose = require("mongoose");
  3. Assign a MongoDB connection string to uri and declare the options settings using the following code:

    var uri = "mongodb+srv://username:[email protected]/test?retryWrites=true";
    
    
    const options = {
        reconnectTries: Number.MAX_VALUE,
        poolSize: 10, 
        useNewUrlParser:true
      };)
  4. Connect the application to MongoDB Atlas using the following code:

      mongoose.connect(uri, options).then(
        () => {
          console.log("Database connection established!");
        },
        err => {
          console.log("Error connecting Database instance due to: ", err);
        }
      );
  5. Create a folder named api (inside config), a subfolder models (inside api) inside it, and then create an Article.js.

    Code for creating the api folder:

    mkdir api

    Code for creating the models folder:

    mkdir models

    Code for creating the Article.js file:

    touch Article.js
  6. Declare the schema and assign a schema class in the Article.js file. First we import Mongoose using the following code:

    const mongoose = require("mongoose");

    To declare and assign schema, we use the following code:

    const Schema = mongoose.Schema;

    To create the schema instance and add schema properties, use the following code:

    const BlogSchema = new Schema({
      title: {
        type: String,
        required: true
      },
      body: String,
      tag: {
        type: String,
        enum: ['POLITICS', 'ECONOMY', 'EDUCATION']
      },
      createdOn: {
        type: Date,
        default: Date.now
      }
    });
  7. Create the default Mongoose model.

    To create the model, we first call mongoose on model() function to use the default mongoose connection using the following code:

    mongoose.model();

    Then, pass the model name as the first argument:

    mongoose.model("ArticleModel");

    Pass the schema name(BlogSchema) as the second argument:

    mongoose.model("ArticleModel", BlogSchema);

    Make model exportable using the following code:

    module.exports = mongoose.model("ArticleModel", BlogSchema);
  8. Create an output.js file and import model using the following code:

    const Article = require("../models/Article");
    
    if(Article){
        console.log('Model Succesfully Imported');
    }
  9. Run the output.js file to confirm whether the model has been imported using the following code:

    node output

    You will obtain the following output:

    Figure 2.18: Model successfully imported

  10. Run node db.js inside the config folder to test the connection using the following code:

    node db.js

    You will obtain the following output:

    Figure 2.19: Testing the connection

Activity 4: Creating Controllers for API

  1. Create a folder named controllers as a subfolder inside api, and then open the controllers folder and create an articleListController.js file.

    To create the controllers folder, use the following code:

    mkdir controllers 

    To create the articleListController.js, use the following code:

    touch articleListController.js
  2. Open the articleListController.js file and import the model using the following code:

    const Article = require("../models/Article");
  3. Create a controller to list all articles using the following code:

    exports.listAllArticles = (req, res) => {
      Article.find({}, (err, article) => {
        if (err) {
          res.status(500).send(err);
        }
        res.status(200).json(article);
      });
    };
  4. Create a controller to create new articles using the following code:

    exports.createNewArticle = (req, res) => {
      let newArticle = new Article(req.body);
      newArticle.save((err, article) => {
        if (err) {
          res.status(500).send(err);
        }
        res.status(201).json(article);
      });
    };
  5. Create a controller to read articles using the following code:

    exports.readArticle = (req, res) => {
      Article.findById(req.params.articleid, (err, article) => {
        if (err) {
          res.status(500).send(err);
        }
        res.status(200).json(article);
      });
    };
  6. Create a controller to update articles using the following code:

    exports.updateArticle = (req, res) => {
      Article.findOneAndUpdate(
        { _id: req.params.articleid },
        req.body,
        { new: true },
        (err, article) => {
          if (err) {
            res.status(500).send(err);
          }
          res.status(200).json(article);
        }
      );
    };
  7. Create controller to delete articles using the following code:

    exports.deleteArticle = (req, res) => {
      Article.remove({ _id: req.params.articleid }, (err, article) => {
        if (err) {
          res.status(404).send(err);
        }
        res.status(200).json({ message: "Article successfully deleted" });
      });
    };

Activity 5: Creating the API Express Route and Testing a Fully Functional RESTful API

  1. Create a routes folder within the api folder and create an articleListRoutes.js file using the following code:

    touch articleListRoutes.js
  2. Open the articleListRoutes.js and create a route function using the following code:

    module.exports = function(app) { }
  3. Import controller into route function using the following code:

    module.exports = function(app) {
    var articleList = require('../controllers/articleListController');
    }
  4. Create route for get and post requests on /articles using the following code:

    module.exports = function(app) {
      var articleList = require('../controllers/articleListController');
    app
      .route("/articles")
      .get(articleList.listAllArticles)
      .post(articleList.createNewArticle);
    }
  5. Create route for get, put, and delete requests on /articles/:articleid using the following code:

    module.exports = function(app) {
      conts articleList = require('../controllers/articleListController');
    app
      .route("/articles")
      .get(articleList.listAllArticles)
      .post(articleList.createNewArticle);
    app
      .route("/articles/:articleid")
      .get(articleList.readArticle)
      .put(articleList.updateArticle)
      .delete(articleList.deleteArticle);
    }
  6. Install Express and the bodyParser module using the integrated command line.

    To do this, first open server folder in the Blogging Application folder by using the keyboard combination Ctrl + O or Ctrl + k from VSC and enable the integrated terminal with Ctrl + '. Then, install Express and the bodyparser module using the following code

    npm install express – save
    npm install bodyparser – save
  7. Create a server.js file in the Blogging Application/config folder and then import Express and the body-parser module using the following code:

    const express = require("express");
    const bodyParser = require("body-parser");
  8. Create the Express application using the express() function:

    const app = express();
  9. Define the connection port

    const port = process.env.PORT || 3000;
  10. Call the bodyParser middleware on the created Express app using the following code:

    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
  11. Import the db connection:

    require("./config/db");
  12. Add CORS (Cross-Origin Resource Sharing) headers to support cross-site HTTP requests

    app.use(function(req, res, next) {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
      // allow preflight
      if (req.method === 'OPTIONS') {
          res.send(200);
      } else {
          next();
      }
    });
  13. Import the route using the following code:

    conts routes = require('./api/routes/articleListRoutes');
  14. Call route on the Express application using the following code:

    routes(app);
  15. Listen to the Express server

    app.listen(port, () => {
      console.log('Server running at http://localhost:${port}');
    });
  16. Run server.js inside the server folder to test the connection using the following code:

    node server.js

    You will obtain the following output:

    Figure 2.20: Database connection established

  17. Open Postman and test the API.

  18. Post a new article to localhost:3000/articles using the POST request as shown:

    Figure 2.21: Implementing the POST request

  19. Get the posted articles by id on localhost:3000/articles/:id using the GET request as shown:

    Figure 2.22: Implementing the GET request by id

  20. Get all posted articles by id on localhost:3000/articles using GET request as shown:

    Figure 2.23: Implementing the GET all posts request

  21. Update posted articles by id on localhost:3000/articles/:id using the PUT request as shown:

    Figure 2.24: Updating using the PUT request by id

  22. Delete posted articles by id on localhost:3000/articles/:id using DELETE request as shown:

    Figure 2.25: Implementing the DELETE request

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image