Skip to main content

Managing MongoDB Records Using NestJS and Mongoose

NestJS is a framework for developing Node.js-based applications. It provides an additional abstraction layer on top of Express or other HTTP handlers and gives developers a stable foundation to build applications with structured procedures. Meanwhile, Mongoose is a schema modeling helper based on Node.js for MongoDB.

There are several main steps to be performed for allowing our program to handle MongoDB records. First, we need to add the dependencies which are @nestjs/mongoose, mongoose, and @types/mongoose. Then, we need to define the connection configuration on the application module decorator.

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

@Module({
  imports: [
    MongooseModule.forRoot('mongodb://localhost:27017/mydb'),
  ],
  controllers: [AppController],
  providers: [AppService],
})

Next, we create the schema definition using helpers provided by NestJS and Mongoose. The following snippet is an example with a declaration of index setting and an object as the value of a field.

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

@Schema()
export class User extends Document {
  @Prop()
  name: string;

  @Prop({ index: true }) // set index individually
  type: string;

  @Prop(SchemaTypes.Mixed) // a value with type of object
  payload: Record<string, any>;
}

export const UserSchema = SchemaFactory.createForClass(User);
UserSchema.index({ name: 1, type: -1 }); // set compound index

Now, we can set the schema as a property for the Mongoose module imported into any application module.

//...
  imports: [
    MongooseModule.forFeature([
      {
        name: User.name,
        schema: UserSchema,
      },
    ]),
  ],
//...

Finally, we can inject the model of our schema into a component in our application. For instance, we will inject it into a service using the InjectModel decorator.

import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';

@Injectable()
export class UserService {
  constructor(
    @InjectModel(User.name) private readonly userModel: Model<User>,
  ) {}

  findAll() {
    return this.userModel
      .find()
      .skip(0)
      .limit(10)
      .exec();
  }
  
  create(data) {
    const user = new this.userModel(data);
    return user.save();
  }
  
  async update(id: string, data) {
    const existingUser = this.userModel
      .findOneAndUpdate({ _id: id }, { $set: data }, { new: true }) // return the updated object
      .exec();

    if (!existingUser) {
      throw new NotFoundException();
    }

    return existingUser;
  }
  //...

Additionally, in a database operation, we may be required to perform a transaction that updates records in several collections. We can realize it by injecting a connection to our service and creating a session for the transaction.

import { InjectModel, InjectConnection } from '@nestjs/mongoose';
import { Model, Connection } from 'mongoose';

@Injectable()
export class TeaService {
  constructor(
    @InjectModel(User.name) private readonly userModel: Model<User>,
    @InjectModel(Related.name) private readonly relatedModel: Model<Related>, // an example of another schema
    @InjectConnection() private readonly connection: Connection,
  ) {}
  // ...
  
  async duSomething(user: User) {
    const session = await this.connection.startSession();
    session.startTransaction();

    try {
      user.numberOfRelation++; // an example of a field update
      
      const related = new this.relatedModel({
        name: 'something',
        payload: { userId: user._id },
      });

      await related.save({ session });
      await user.save({ session });

      await session.commitTransaction();
    } catch (error) {
      await session.abortTransaction();
    } finally {
      session.endSession();
    }
  }

Comments

Popular posts from this blog

Deploying a Web Server on UpCloud using Terraform Modules

In my earlier post , I shared an example of deploying UpCloud infrastructure using Terraform from scratch. In this post, I want to share how to deploy the infrastructure using available Terraform modules to speed up the set-up process, especially for common use cases like preparing a web server. For instance, our need is to deploy a website with some conditions as follows. The website can be accessed through HTTPS. If the request is HTTP, it will be redirected to HTTPS. There are 2 domains, web1.yourdomain.com and web2.yourdomain.com . But, users should be redirected to "web2" if they are visiting "web1". There are 4 main modules that we need to set up the environment. Private network. It allows the load balancer to connect with the server and pass the traffic. Server. It is used to host the website. Load balancer. It includes backend and frontend configuration. Dynamic certificate. It is requ...

Armin or Commander Erwin

In the moment of conflict in the scout team, who will be revived?

What's Good About Strapi, a Headless CMS

Recently, I've been revisiting Strapi as a solution for building backend systems. I still think this headless CMS can be quite useful in certain cases, especially for faster prototyping or creating common websites like company profiles or e-commerce platforms . It might even have the potential to handle more complex systems. With the release of version 5, I'm curious to know what updates it brings. Strapi has launched a new documentation page, and it already feels like an improvement in navigation and content structure compared to the previous version. That said, there's still room for improvement, particularly when it comes to use cases and best practices for working with Strapi. In my opinion, Strapi stands out with some compelling features that could catch developers' attention. I believe three key aspects of Strapi offer notable advantages. First, the content-type builder feature lets us design the data structure of an entity or database model , including ...

Kenshin VS The Assassin

It is an assassin versus assassin.

Rangkaian Sensor Infrared dengan Photo Dioda

Keunggulan photodioda dibandingkan LDR adalah photodioda lebih tidak rentan terhadap noise karena hanya menerima sinar infrared, sedangkan LDR menerima seluruh cahaya yang ada termasuk infrared. Rangkaian yang akan kita gunakan adalah seperti gambar di bawah ini. Pada saat intensitas Infrared yang diterima Photodiode besar maka tahanan Photodiode menjadi kecil, sedangkan jika intensitas Infrared yang diterima Photodiode kecil maka tahanan yang dimiliki photodiode besar. Jika  tahanan photodiode kecil  maka tegangan  V- akan kecil . Misal tahanan photodiode mengecil menjadi 10kOhm. Maka dengan teorema pembagi tegangan: V- = Rrx/(Rrx + R2) x Vcc V- = 10 / (10+10) x Vcc V- = (1/2) x 5 Volt V- = 2.5 Volt Sedangkan jika  tahanan photodiode besar  maka tegangan  V- akan besar  (mendekati nilai Vcc). Misal tahanan photodiode menjadi 150kOhm. Maka dengan teorema pembagi tegangan: V- = Rrx/(Rrx + R2) x Vcc V- = 150 / (1...

How To Verify Phone Number for Free Using WhatsApp

If you have a product or business that maintains user information like phone numbers, verifying the validity or ownership of the phone number could become important, as the phone number can be used as an authentication method or targeted marketing channel. The typical phone verification procedure is by generating a code or OTP in our application, sending that OTP to the user's phone, and then the user should insert the OTP in our application for verification. The OTP can be sent to the users through services like SMS or WhatsApp that require a valid phone number. For internet-based communication, WhatsApp has become the de facto standard for sending the OTP. WhatsApp requires its users to have a valid phone number during account creation, and it already has a huge number of users, approximately 3 billion in 2025. Using that common procedure, WhatsApp will charge us for each OTP sent. The cost depends on the country of the target phone number. For Indonesia...