- 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.
Navigate to the
srcfolder and create a
services.jsfile inside both the
The 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.
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.
- 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.