How to create models and schemas for the API endpoints with Mongoose
In this article, we will create models and schemas for the Author and Book objects that we need for API endpoints.
Models
Run this command to install mongoose:
npm i mongoose
Let’s create a schema and a model for the object author. The authors should have first and last names, biography, dates of birth, and death (optional). Create a new file authors.js
in this location src/services/authors/models/
and paste this code into it:
In this file, we create the schema. We specify types and if the property is required or not. Then we use this schema to create a model named AuthorModel
.
We set dateOfBirth
and dateOfDeath
to have type Date
and as a result, it will have a timestamp. We also want to store the exact dates users will input (the date should not be dependent on any timezone). So, before saving a new Author object, we will convert both dates, set values for hours, minutes, and seconds to be 0. We will do that in a pre-save hook.
Add this code before the last line where we create the author model:
The code inside pre-save hook is run after validation so we can be sure that the dates are valid when we prepare the data for saving. The dateOfBirth
is required so we can freely do new Date(this.dateOfBirth)
but dateOfDeath
is not required so we call getUTCDateNoTime
only when it is not undefined
.
Now we will create the book model. Create a new file src/services/books/models/books.js
with this content:
Books will have a title, description, and author id, which references the AuthorModel we previously created. Title and reference to the author should be required. We also create an index for the authorId
property.
Summary
In this article, we have created schemas and models for two objects with required properties, created an index, and made one property to be a reference to another model. We also added pre-save hook to our model to do the changes to the provided data before saving it to the database.
This is the second part of the “How to develop API with Node.js and Express” series. If you want to follow along read the previous article where we set up the project. The whole project is on GitHub.