skip to Main Content

I return a mongoose find query in a nextjs (version 13.5) server action and encounter ‘Maximum call stack size exceeded’ error. I think the main cause of the problem is mongoose populate method because when I remove it, the error doesn’t display anymore :

Error: Maximum call stack size exceeded

Call Stack
String.replace
<anonymous>
_e
file:///C:/Users/hossein/homebnb/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js (1:447398)
Re
file:///C:/Users/hossein/homebnb/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js (1:448056)
Re
file:///C:/Users/hossein/homebnb/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js (1:449122)
Re
file:///C:/Users/hossein/homebnb/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js (1:449122)
Re
file:///C:/Users/hossein/homebnb/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js (1:449122)
Re
file:///C:/Users/hossein/homebnb/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js (1:449122)
Re
file:///C:/Users/hossein/homebnb/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js (1:449122)

my server action:

import { Types } from "mongoose";
import Reservation from "@/models/Reservation";

interface IParams {
  listingId?: string;
  userId?: string;
  authorId?: string;
}

export default async function getReservations(params: IParams) {
  const { listingId, userId, authorId } = params;

  const query: any = {};

  if (listingId) {
    query.listingId = new Types.ObjectId(listingId);
  }

  if (userId) {
    query.userId = userId;
  }

  if (authorId) {
    query.listing = { userId: authorId };
  }

  console.log("QUERY: " + JSON.stringify(query));
  try {
    const reservations = await Reservation.find(query)
      .populate({ path: "userId", select: "name" })

      .then((p) => {
        return p;
      })
      .catch((error) => console.log(error));

    console.log("REsSSSSS" + reservations);

    return reservations;
  } catch (error: any) {
    throw new Error(error);
  }
}

2

Answers


  1. Chosen as BEST ANSWER

    I resolved the error by adding .lean() method to the end of mongoose query like this:

    const reservations = await Reservation.find(query).populate({ path: "userId", select: "name" }).lean();
    

  2. You just have to update your try and catch logic and it will work.

    try {    
        const reservations = await Reservation.find(query)
        .populate({ path: "userId", select: "name" })
    
        if (!reservations) {
           throw new Error("No reservations found.");
        }
    
        console.log("RESERVATIONS: " + JSON.stringify(reservations));
        
        return reservations; 
    } catch (error: any) {    
        throw new Error(error);    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search