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
I resolved the error by adding .lean() method to the end of mongoose query like this:
You just have to update your
try and catch
logic and it will work.