Table of content
What is a service layer?
- The service layer is where we hold our business logic.
- This layer receives data and tasks from the controller layer. It performs its specific task and returns the processed data to the controller.
- The service layer uses a data model to access database functionality and perform an operation on the database.
- It doesn't handle HTTP requests and responses directly.
In your Node.js project, navigate to the
srcfolder and create a
services.jsfile inside both the
The Node.js project structure will look something like this:
We will import the Author model and use provided functions to perform various operations on the author's documents.
The functions created below hold the logic to complete a particular operation or task.
Each function uses a model instance to perform database operations.
Each function can receive data from the respective controller.
After completing the task, each function returns processed data to controller.
./src/author/services.jsfile put the below code.
We will repeat the same steps for post services.
populate(): Since we have structured our post schema to hold the author's reference. We can use the
populate()function to fill the
authorReffield with author's information. In this case, we are only interested in the author's name. We can use a comma-separated string to include other fields from the author.
./src/post/services.jsfile put the below code.
- We have created schemas for the
- In the next part, we will create the controller for each collection.
- The link to the project repo is available here.