Utilizing MongoDB in Node.js Environment

I am currently facing an issue with connecting to a larger database through node. In the past, I have successfully connected to smaller databases using a Mongo URL in this format:

mongodb://[username]:[password]@db1-a0.example.net:27017/[DB-Name]

However, when attempting to connect to a larger DB using the following Mongo URL:

mongodb://[username]:[password]@db1-a1.example.net:27017,db2.example.net:2500/[DB-Name]?replicaSet=test

An error ' RangeError: Maximum call stack size exceeded' occurs and prevents the connection from being established. The only difference between the two URLs is the database size.

I have verified the database details and confirmed access through RoboMongo / Robo 3T, indicating that the database does indeed exist.

The attempt to establish a connection is made using Mongoose version ^5.2.10 along with the provided code:

function connect() {

    if (MONGO_URL) {
        mongoose.connect(MONGO_URL, err => {
            if (err) {
                console.log('error connecting')
                console.log(err)
            }
        })
    } else {
        mongoose.connect(`mongodb://${host}`, {
            user,
            pass,
            dbName,
            useNewUrlParser: true //depresiation issue
        }, err => {
            if (err) {
                console.log('error connecting')
                console.log(err)
            }
        })
    }
}

mongoose.connection.on('error', (message) => {
    console.log('connection error!') //This is logged
    console.log(message)
    process.exit()
})
mongoose.connection.on('disconnected', connect)


connect()

Answer №1

It seems like you are attempting to utilize a replica set. If that's the case, try connecting using the code snippet below:

var uri = `mongodb://${userName}:${encodeURIComponent(password)}@${clusterName}/${dbName}?ssl=true&replicaSet=${process.env.replicaSetName}&authSource=${authDB}`

var db = mongoose.connect(uri).then().catch() // Add your code inside the then and catch blocks

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

Why does my jQuery map code work in version 2.0 but not in version 3.0?

I've encountered an error with a jQuery map snippet that I'm trying to troubleshoot. It was working fine under jQuery 2, but after upgrading to version 3, it doesn't work anymore and I can't figure out why. Feeling stuck! var menuIte ...

What is the best way to extract the JSON data from a client-side GET request response?

Here is my request from the client side to the server in order to retrieve JSON data. fetch("/" + "?foo=bar", { method: "GET", }).then(response => { console.log(" ...

Attempting to move elements into an array for storage in the local storage

Is there a way to properly add elements to an array and store it in localstorage? Here's the code snippet I've been working with: const handleSelectLayouts = (layout) => { const layoutsArray = []; layoutsArray.includes(layout) ...

Is it possible to pass additional arguments to setState other than prevState and props?

I'm currently facing an issue with my component that involves calling a function called addOption, which is defined on its parent component. This function takes a parameter 'option' from a form field and concatenates it with an array of opti ...

Different ways to shuffle the arrangement of divs

Forgive me if this seems like a simple query, but I am struggling with it. Essentially, what I want to achieve is to randomize the positioning of the items, where item 1 can adopt the style of item 3 (or 2 or 4), item 2 can take on the style of 1, 3, or 4, ...

LazyTreeGrid from Dojo encounters issues with paginating children while using QueryReadStore

Currently, I am experimenting with the LazyTreeGrid implementation in Dojo and have encountered an issue. When LazyTreeGrid is paired with LazyTreeGridStoreModel and QueryReadStore for pagination of children nodes, errors sometimes arise. I attempted to l ...

Retrieving data from a directive in an HTML table

Utilizing AngularJS, I am seeking a method to retrieve the value from an input located within a specific row in a table. Presented below is an input element. Upon clicking the "add" button, my objective is to extract the value corresponding to that partic ...

Change the value of input on onClick event in React

Although this may seem simple, it is a little confusing to me. I'm having trouble understanding why the input value in the following case is not being reset. handleReset() { this.setState({ data: "" }); } <button onClick={this.handleReset}>R ...

Is it possible for me to introduce an additional variable to the String.prototype object?

I have a question that has been bugging me out of curiosity. I was thinking about whether I can add an additional variable in front of String.prototype. For instance: $.String.prototype.functionName = function(){}; Obviously, this doesn't work as i ...

This error message occurs when trying to access JSON keys from an object with an invalid operand in the 'in' operation

Check out the fiddle I created here: http://jsfiddle.net/kc11/h6nh1gvw/2/ I'm attempting to extract keys from a JSON string using this code: var keys = $.map(a, function(element,key) { return key; }); . But unfortunately, I keep encountering the er ...

"Exploring the power of asynchronous programming with dynamic async await in

I am currently working on creating a versatile function that can dynamically call async functions. //passing the controller and functionName (string) function asyncAwaitCaller(controller, functionName) { let result = await controller[functionName]; } ...

Encountered an error while trying to retrieve data from

Having trouble with file uploads to the S3 bucket using @aws-sdk/client-s3 library and encountering errors when uploading files larger than 70kbps: `TypeError: Failed to fetch at FetchHttpHandler.handle (fetch-http-handler.js:56:13) at PutObjectCommand ...

Using Three.js to create a React button positioned above a canvas

Here's the code I have written using three.js in a React component. I am looking to add a button above the canvas. How can I achieve this? Additionally, I would like to know how to add a click event on objects rendered in three.js. import React, { Com ...

What is the best way to clear the cache in AngularJS?

It is crucial for the cache to be cleared consistently. However, no matter if a client is created, updated, or deleted, the same result always occurs. Only when I manually delete the cache (Ctrl+Shift+Supr), am I able to view the new data. .factory(' ...

Understanding the getJSON MethodExplaining how

$.getJSON( main_url + "tasks/", { "task":8, "last":lastMsgID } I'm a bit confused about how this code functions. I'm looking for a way to retrieve messages from a shoutbox using a URL or some sort of method that the function here ...

Running tests to check for next(err) functionality using supertest and Express JS

When using Express in a route or middleware, you can halt the callback chain by calling next(err) with any object as err. This feature is well-documented and simple to understand. However, I encountered an issue when testing this behavior with SuperTest. ...

Removing cookies with angular js: A simple guide

I have a list of cookies that contain commas, and I want to remove a specific item when it is clicked. Here is an example of how my cookies are structured: 879273565,879269461,879273569,659234741 artistcontrollers.controller("CartController", ["$scope", ...

Discovering the reason behind a DOM element's visual alteration upon hovering: Where to start?

Visit this page, then click on the next button to navigate to the time slots section. As you hover over any time slot, you will notice a change in appearance. Despite inspecting Chrome's developer tools, I was unable to locate a style with a hover dec ...

Countdown Timer App using Flask

I'm currently working on a Flask-based game that involves countdown timers for each round. My goal is to have the timer decrease by 1 second every round without the need to reload the page. I've tried using time.sleep in my Python code to update ...

Does the TS keyof typeof <Object> rule prohibit the assignment of object.keys(<Object>)?

I'm having trouble understanding the issue with this code snippet. Here is the piece of code in question: export type SportsTypes = keyof typeof SportsIcons export const sports: SportsTypes[] = Object.keys(SportsIcons); The problem arises when I at ...