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
mongoose
library:$ npm install [email protected]
- Create a new
src/db/init.js
file and importmongoose
there:import mongoose from 'mongoose'
- Define and export a function that will initialize the database connection:
export function initDatabase() {
- First, we define
DATABASE_URL
to point to our local MongoDB instance running via Docker and specifyblog
as the database name:const DATABASE_URL = 'mongodb://localhost:27017/blog'
The connection...