Home > Enterprise >  Total JS heap size increases about 120MB when placing a mongodb query
Total JS heap size increases about 120MB when placing a mongodb query

Time:10-22

I don't understand why heap size keeps increasing when i place a mongodb database query inside a function in my controller.

here is my router

import { Router } from "express";
import profileController from '../controllers/profileController';

class userRouter {
  public router: Router;

  constructor() {
    this.getRoutes();
  }

  getRoutes() {
    this.router.get("/profile-list", profileController.getProfileList);
  }
}

export default new userRouter().router;

here is my controller

import Profile from "../models/profile";

export class profileController {
  static async getProfileList(req: any, res: any, next: any) {
    try {
      const getList = await Profile.find();
      res.status(200).json({
        status: 200,
        message: "Success",
        data: getList,
      });
    } catch (error) {
      console.log(error);
    }
  }
}

here is my model

import * as mongoose from "mongoose";
import { model } from "mongoose";

const profileSchema = new mongoose.Schema({
  userId: { type: String, required: true },
  name: { type: String,  default: ""},
},
{ timestamps: true }
);

export default model("profile", profileSchema);

Total heap size without getProfileList function => 135 MB

Total heap size after placing getProfileList function => 255 MB (specifically after putting const getList = await Profile.find(); )

Here I inspected the memory and found this in comparison:

TypeObject increased from 3MB to 99MB (array) increased from 26MB to 88MB

Any please please help me understand why does it happen? or is it usual in such case.

Screenshot of the comparison before and after

CodePudding user response:

The problem is that you are not using any limits, so using await Profile.find(); will return all the documents in the database, so when you are making a call to your controller that will return all data from the database that can incresase the heap size a lot.

You can use limit and skip to implement pagination for your endpoint.

Also you should consider the fact that Mongoose library has to be loaded into your memory, connections to database and so on, that also requries RAM.

  • Related