Creating database schemas using Mongoose
Before we can get started defining the database schemas, we first need to set up Mongoose itself. Mongoose is a library that simplifies MongoDB object modeling by reducing the boilerplate code needed to interface with MongoDB. It also includes common business logic such as setting createdAt and updatedAt timestamps automatically and validation and type casting to keep the database state consistent.
Follow these steps to set up the mongoose library:
- First, install the
mongooselibrary:$ npm install mongoose@8.0.2
- Create a new
src/db/init.jsfile and importmongoosethere:import mongoose from 'mongoose'
- Define and export a function that will initialize the database connection:
export function initDatabase() { - First, we define
DATABASE_URLto point to our local MongoDB instance running via Docker and specifyblogas the database name:Â Â const DATABASE_URL = 'mongodb://localhost:27017/blog'
The connection...