Create Service

In this part we will create a service that contains our business logic. This service will be called book.service.js and should be located in the /services folder.

As we will be manipulated data in our service, we need to import our book model that we have defined earlier.

const Book = require("../models/Book")

We will then create a function bookService() that will contain all the methods that we want to implement.

In this tutorial, we will define three methods: getBooks() which will retrieve all the books in the database, addBook() which will be responsible for creating a new book in the database and deleteBook() which will delete a book from the database.

function bookService() {
  async function getBooks() {
    return Book.find({})
  }

  async function addBook(title, author, isbn) {
    return Book.create({Title: title, Author: author, ISBN: isbn})
  }

  async function deleteBook(isbn) {
    return Book.deleteOne({ISBN: isbn})
  }

  return {
    getBooks,
    addBook,
    deleteBook
  }
}

Finally, we only need to export our service. Exporting our service will allow us to use it elsewhere in the program (just like how we used the book model in the book service module).

module.exports = bookService;

Last updated