LogoLogo
  • Introduction
  • Backend
    • Creating a MongoDB Database
    • Environment Variables
    • Configuring the Mailing Service
    • Seeding the Database
    • Starting the Backend
  • Frontend
    • Starting the Frontend
  • Book Module Tutorial
    • Introduction
    • Backend
      • Create Model
      • Create Service
      • Create Route
      • Test using Postman
    • Frontend
      • Introduction
      • File Structure
      • Defining Concepts
      • Display App in Dashboard
      • Create Module
      • Create Book List Component
      • Create Main Component
      • Create Service
      • Display Book List
      • Add a Book
        • Update Service
        • Create Component
        • Final Code Review
      • Delete a Book
        • Update Service
        • Update Component
        • Final Code Review
      • Conclusion
  • Resources
  • Beginner
  • Advanced
  • Recommended Extensions for Visual Studio Code
  • Troubleshooting
    • Troubleshooting
Powered by GitBook
On this page

Was this helpful?

Export as PDF
  1. Book Module Tutorial
  2. Backend

Create Service

PreviousCreate ModelNextCreate Route

Last updated 4 years ago

Was this helpful?

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;