Using a MongoDB database in a NestJS app with Mongoose

MongoDB is a schemaless NoSQL database with flexible document structures, unlike SQL databases. Using MongoDB as a database brings many benefits, from easy scaling to modern database features like transactions.

MongoDB also supports object data modeling (ODM) libraries such as Mongoose. ODMs manage data relationships, validate schemas, and convert objects into data models. They make it easy to interact with a MongoDB database.

In a few steps, you will learn how to use MongoDB in a NestJS application with the dedicated mongoose NestJS package.

Step 1: Install dependencies

Before using Mongoose in your NestJS application, you must install it with its native NestJS package.

Install mongoose and its native NestJS package using the npm package manager by running:

npm install @nestjs/mongoose mongoose

Step 2: Connect to MongoDB

Once the installation is complete, go to your app.module.ts case. Then import Mongoose Module of @nest/mongoose:

import { MongooseModule } from '@nestjs/mongoose';

Then in your imports array call the forRoot method on Mongoose Module and pass your MongoDB URI as an argument:

imports: [MongooseModule.forRoot(process.env.MONGODB_URI)],

The forRoot The method shares the database connection through all modules of your application. It takes an optional configuration object; you can read more about it in Mongoose documentation of options.

Step 3: Creating a Mongoose Schema

A schema is a JSON object that defines the structure and content of your data. You will need to create one to define how Mongoose stores your data in the MongoDB database.

In the root module of your application, create a “diagramsfolder. This folder is where you will store all of your schema files.

Inside your diagrams folder, create a schema file and name it using the NestJS naming convention (.schema.ts).

Next, add the following imports to your schema file:

import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { Document } from "mongoose";

The Sustain the decorator marks the properties it annotates as a property in your MongoDB database.

The Plan decorator marks the class it annotates as a schema.

The SchemaFactory The class contains static methods used for creating models.

Mongoose Document represents a one-to-one mapping to documents as stored in MongoDB. You will need it as a type annotation.

Next, create a class, annotate it with the Plan decorator to mark it as a Mongoose schema and export it:

export class Demo {}

Next, create and export a union type with your class and Document:

export type DemoDocument = Demo & Document;

Then add the desired properties to the class and annotate them with the Sustain decorator. You can pass an optional configuration object to the Sustain decorator and set the property as needed:

export class Demo {
@Prop({ required: true })
property_1: string;

The Mongoose The documentation covers the configuration object in more detail.

Finally, create and export a Mongoose model via the SchemaFactoryit is createForClass method and pass your class as an argument:

export const DemoSchema = SchemaFactory.createForClass(Demo);

Your finished diagram should look like this:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

export type DemoDocument = Demo & Document;

export class Demo {
@Prop({ required: true })
property_1: string;

@Prop({ required: true })
property_2: number;

property_3: string;

@Prop({ required: true })
property_4: boolean;

export const DemoSchema = SchemaFactory.createForClass(Demo);

Step 4: Save the Schema

Navigate to your module folder and add the following imports:

import { MongooseModule } from '@nestjs/mongoose';
import { Demo, DemoSchema } from '../schemas/demo.schema';

Then create a “imports” table inside the @module decorator. Then, inside the array, call the for Feature method on Mongoose Module.

The for Feature The method supports an array of Mongoose models. Pass a configuration object with a Last name property set to the name of your schema class, and a plan property set on your created schema:

MongooseModule.forFeature([{ name:, schema: DemoSchema }]),

Step 5: injection of the mongoose model

Next, you will need to inject the Mongoose model to enable querying your database by calling Mongoose methods on the model.

Navigate to your module’s service class and add the following imports:

import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { Demo, DemoDocument } from '../schemas/demo.schema';

Use the Model interface as the type definition for your model, giving it access to Mongoose methods.

The InjectModel decorator injects the Mongoose model into the constructor of your service class.

Then create a constructor within your class of service. It should take a private variable as an argument, a Model with a generic type of Demo Document. Annotate your private variable with the InjectModel decorator and pass your schema class name as an argument:

export class DemoService {
private demoModel: Model<DemoDocument>,
) {}

You can query your MongoDB database by calling Mongoose methods on your private variable (demonstration model).

Benefits of Using MongoDB

Along with its strong online community and ease of use, MongoDB offers high data availability and stability. It offers accelerated analytics, data aggregation, and more, making it the perfect database for your projects.

Source link

Comments are closed.