MongoDB is an excellent NoSQL database.

In this tutorial, we will create an Node.js application that stores books for an established bookstore.


Prerequisites

  1. Node.js
  2. MongoDB
  3. Compass for MongoDB

Start up MongoDB

Open up Command Prompt. Type in,

mongod

This will start a MongoDB server on localhost on port 27017 by default.

Open up Compass and connect to the MongoDB. It allows you to inspect the data much easier without the need of shell commands.

Connect to Local MongoDB using Compass

Create a new project

Clone the simple Node.js project here.

New to Node.js? Refer to this link for a detailed walkthrough.

Install NPM packages,

npm install body-parser express mongoose

Run it locally using,

node app.js

Go to localhost:3000 and "Hello World" should appear on the screen.

Create the data model

Since we're saving records of our favorite books, let's define how our book model.

Create a new file, book/book.model.js

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var bookSchema = new Schema({
  title: String,
  author: String,
  rating: Number,
});

var bookModel = mongoose.model("book", bookSchema, "book");

module.exports = bookModel;

Create the service layer

As part of best practices, it is always better to have a set of standardized functions like createBook, getBooks  instead of interfacing with the model directly from the main application. This also makes it much easier to add unit tests.

Create a new file, book/book.service.js

const addBook = (Book) => (title, author, rating) => {
  if (!title || !author || !rating)
    throw new Error(
      "Missing Data. Please provide values for title, author, and rating."
    );
  const book = new Book({ title, author, rating });
  return book.save();
};

const listBooks = (Book) => () => {
  return Book.find({});
};

module.exports = (Book) => {
  return {
    addBook: addBook(Book),
    listBooks: listBooks(Book),
  };
};

Create a new file, book/index.js

const Book = require("./book.model");
const BookService = require("./book.service");

module.exports = BookService(Book);

Add API endpoints

Let's set up the API endpoints that will be used to add and list books currently available in the bookstore.

Create a file called, app.js

"use strict";
var express = require("express");
var bodyParser = require("body-parser");
var mongoose = require("mongoose");

const BookService = require("./book");

var app = express();

mongoose.Promise = global.Promise;

var uri = "mongodb://localhost:27017/bookstore";
mongoose.connect(uri, {
  useUnifiedTopology: true,
  useNewUrlParser: true,
});

app.use(
  bodyParser.urlencoded({
    extended: false,
  })
);
app.use(bodyParser.json());

app.get("/listBooks", async function (req, res, next) {
  try {
    const books = await BookService.listBooks();
    res.json(books);
  } catch (e) {
    next(e);
  }
});

app.get("/addBook", async function (req, res, next) {
  const title = req.query.title;
  const author = req.query.author;
  const rating = req.query.rating;

  try {
    const books = await BookService.addBook(title, author, rating);
    res.json(books);
  } catch (e) {
    next(e);
  }
});

app.listen(3000, "0.0.0.0", function () {
  console.log("server starting on localhost:3000");
});

Test out the application

Start the application by running,

node app
Start command for bookstore application

Let's open up Postman and try adding a new book.

Adding a new book to the bookstore using Postman

We can open up Compass and confirm that the book record has indeed been added.

Let's try listing all the available books.

bdcorps/node-mongoose-mocha
Contribute to bdcorps/node-mongoose-mocha development by creating an account on GitHub.
View complete source code on Github

Next Steps

In this tutorial, we connected our local MongoDB server to our Node.js application so we can save and read data. Add endpoints for updateBook and deleteBook to build more functionality. Add a simple HTML page that makes it easy for a user to create and list books.