Issue encountered: Runtime stack overflow when trying to clone deep objects using lodash.clonedeep, while attempting to create a sessionMongo

Update: It seems that there might be a deeper issue at play here, unrelated to the import of lodash.

It appears that within the codebase I inherited, the function cloneDeep is being used in multiple instances, and it's possible that there is a circular reference causing problems with the cloning process. If this is indeed the case, I will address this issue and likely encounter some other issues along the way.

nodeJS v14.20.0
typescript v4.6.4
mongodb v4.9.1
mongoose v6.6.1
connect-mongodb-session v3.1.1
lodash v4.17.21

During an upgrade process across various levels, the main obstacle encountered was configuring and connecting to MongoDB using mongoose while switching from connect-mongo to connect-mongodb-session. The build completed without errors, but running the application led to the following:

/Users/.../node_modules/lodash.clonedeep/index.js:841 
function baseClone(value, isDeep, isFull, customizer, key, object, stack) {
                  ^
RangeError: Maximum call stack size exceeded 
   at baseClone (/Users/.../node_modules/lodash.clonedeep/index.js:841:19)
   at /Users/.../node_modules/lodash.clonedeep/index.js:897:30
...

This error occurred during mongoose configuration:

import mongo from 'connect-mongodb-session';
import mongoose from './db'

const MongoStore = mongo(session);

...

const sessionMongoStore = new MongoStore({
      autoReconnect: true,
      mongooseConnection: mongoose.connection
    });
    app.use(
      session({
        secret: 'Pnv68aFuBy',
        store: sessionMongoStore,
        resave: true,
        saveUninitialized: true,
      })
    );

The db.ts file extends mongoose to provide a properly configured connection and contains the following:

import assert from 'assert';
import mongoose from 'mongoose';
import appEnv from './appenv';
import bluebird from 'bluebird';
import * as _ from 'lodash';

(mongoose as any).Promise = bluebird;
 
...

mongoose.connect( connectionString)
  .then( () => { /* resolves to undefined */})
  .catch(err => {
    console.log('MongoDB connection error: ' + err);
  });

export default mongoose;

All of this was functioning correctly with the previous versions listed below:

nodeJS v12.22.12
typescript v3.8.3
mongodb v3.3.13
mongoose v5.9.12
connect-mongo v3.1.2
lodash v4.17.13

I am considering whether including the db.ts file is causing an infinite recursion issue for lodash.

Answer №1

After navigating through distractions, the issue did not stem from user code but rather from a node module that was installed - specifically, the problematic usage of app.use(helmet.noCache()); which included the incorrect application of lodash.cloneDeep.

A coworker suggested substituting lodash.cloneDeep with clone. They advised to "...set the circular attribute to true (then gradually switch it to false in certain areas until an error occurs)". Since all references were successful, it was just a matter of investigating the various node modules. The red flag was the notification indicating that helmet.noCache() had become outdated.

Rectifying this issue is straightforward. Within the application code:

  1. add import noCache from 'nocache';
  2. substitute app.use(helmet.noCache()); with app.use(noCache());

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript heap running out of memory after upgrading from Angular 11 to versions 12, 13, or 14

I need assistance with resolving a JS heap out of memory issue that has been occurring when trying to start the local server ever since migrating from Angular 11 to Angular 12 (or 13 or 14, all versions tested with the same problem). This occurs during th ...

Do you know the reason for implementing this CORS error policy?

I am currently working on a project using Angular for the frontend, which is running on localhost:4200. This project will eventually be moved to production. I wanted to mention this in case someone can help me with a solution. Additionally, I have a webser ...

How to leverage async/await within loops in Node.js for optimized performance and efficiency

Hey there, I'm working on my nodejs api where I need to fetch data inside a loop and then perform another loop to save data in a different table. Can anyone guide me on how to achieve this? Below is a snippet of what I have attempted so far without su ...

Visual Studio - Error TS1005 'Unexpected token'

After spending nearly 5 hours scouring the internet for a solution, I am still unable to resolve this persistent issue. The responses I've found so far do not seem to address the specific problem I'm facing. Although I have upgraded the tsc vers ...

Unexpected Union Type Return from Apollo Server

When I call my resolver to return a union type (either a User or an object with a message key and value of type String, such as my UserNotFoundError type), it always comes back with "__typename": "User". Why is this happening and how ca ...

Come together at the table as it expands significantly

My application's MySQL database has a join table that is growing exponentially. I am dealing with 2 models – user and product. A user can view many products, and products can be viewed by multiple users. Initially, all users have access to all prod ...

How can I retrieve information from SafeSubscriber?

I need to develop an Angular application that fetches data from the backend and displays it on the front end, along with some predefined hard-coded data. The communication in my project happens between two files: client.service.ts import { Injectable } f ...

Exploring ways to pass props in functional components in React Native

I am currently exploring how to create an API in React Native with TypeScript without using the class extends component. However, I am struggling to figure out how to access and send props from one const view to another function: App.tsx import React, {us ...

Angular2 Meteor app encounters difficulty locating basic types in Typescript

Every time I try to use Date, I encounter the following error during compilation: 'Date' cannot be found Here is an example of how it is used: var pastEvents = Events.find({ timestamp: { $lt: new Date() }}); Points to Note: The same issu ...

Querying a specific child in MongoDB

I am dealing with a document that contains an array of elements and I need to identify specific entries within it. Here is an example of two entries: { "c": [ { "k": "1", "v": "1" }, ...

The useParams() method results in a null value

When attempting to utilize the useParams() hook in nextjs, I am encountering an issue where it returns null despite following the documentation. Here is my current directory structure: pages ├── [gameCode] │ └── index.tsx Within index.tsx ...

MongoDB Error: E11000 - This key is already in use in the collection

I keep running into a MongoDB duplicate key error while attempting to sign up a new user in my Node.js and Express app. The error message that pops up is: MongoServerError: E11000 duplicate key error collection: test.users index: email_1 dup key: { email: ...

Tips for changing a function signature from an external TypeScript library

Is it possible to replace the function signature of an external package with custom types? Imagine using an external package called translationpackage and wanting to utilize its translate function. The original function signature from the package is: // ...

When trying to access more than two collections from the same database connection using Mongo-lite, it will trigger an error

Trying to access multiple mongo collections from the same db connection using mongo-lite. Below is an example Express app: var express = require('express'); var app = express(); var http = require('http'); var mongolite = require(&apos ...

Aligning the React Navigation header component's bottom shadow/border width with the bottom tabs border-top width

Currently, I am working on achieving a uniform width for the top border of the React Navigation bottom tabs to match that of the top header. Despite my efforts, I am unable to achieve the exact width and I am uncertain whether it is due to the width or sha ...

Is it possible to call a service within an NgFor loop in Ionic/Angular 2?

I am facing an issue with my ngFor directive. Here is the code snippet: <ion-card *ngFor="let review of reviews"> <ion-card-content> {{getUserName(review.user_ID)}} </ion-card-content> </ion-card> The challenge I a ...

Exploring Generics and Type Inference within TypeScript

(In reference to this question) I've developed a function that takes in a configuration object containing state definitions, essentially creating a state machine. For example: const machine = createStateMachine({ initial: 'inactive', s ...

Tips on looping through a dynamic FormControl using Angular2 and FormBuilder

I am facing an issue when trying to iterate over a dynamically generated FormControl in the HTML section. Instead of displaying the expected values, I am getting [object Object],[object Object] in the input field. Here is the provided data structure: { ...

Ways to retrieve subdocument data for numerical keys

I have a mongo document structured like this { "_id" : ObjectId("58a18bdd7313101c38baa06d"), "date" : "2017-02-12", "previsions" : { "1000" : { "tmin" : "3", "tmax" : "13" }, "1090" : { ...

Implementing Retry Functionality with Axios in NestJS

I am integrating a third-party API into my NestJS application to retrieve data and perform certain operations. Occasionally, the API throws a 400 Bad Request error, in which case I need to retry the call after a waiting period of 1 second. What is the best ...