Getting error upon await client.connect() in node.JS

Hi, I’m trying to connect to my mongoDB Atlas via nodejs in my React app, but I’m getting an error cannot read property 'replace' of undefined on await client.connect()

I’m working in Typescript.

Here’s my code to connect. I’ve validated that the connection string works via Compass.

import { MongoClient } from 'mongodb';

const username = encodeURIComponent(process.env.REACT_APP_MONGO_READ_USERID as string);

const userpass = encodeURIComponent(process.env.REACT_APP_MONGO_READ_USERPASS as string);

const uri = `mongodb+srv://${username}:${userpass}@cluster0.xup6s.mongodb.net/ggtavern?w=majority`;

const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

export const getItemsfromMongo = async <T>(collection: string): Promise<T[]> => {

    try {

        console.log(client);

        try {

            await client.connect();

            console.log(client);

        } catch (error) {

            console.error('Failed to connect to MongoDB server');

            throw error;

        }

        const mongoCollection = client.db("ggtavern").collection<T>(collection);

        const cursor = mongoCollection.find()

        const items = await cursor.toArray();

        console.log(items);

        await client.close();

        return items;

    } catch (err) {

        console.error(err);

        return [];

    }

}

First of all, Zachary, I just want to warmly welcome you to the MongoDB Community! We are soooo lucky to have you here, and I am excited to help you troubleshoot your code. :smiling_face_with_three_hearts:

Second, can you send me a link to your code on GitHub, I want to try and run your code locally to see if I can reproduce your error.

My first guess is that your Mongo client hasn’t initialized to the client yet since const client = new MongoClient() is an asynchronous function. If you promisify or add an await on your const client = new MongoClient(), I think that this will solve your problem.

Let me know if that works for you :slight_smile:

@JoeKarlsson
Hi There! I am extremely new to this community and have actually come across this same issue. Adding an await on my const client = new MongoClient() did not work. My code is essentially the same as the gentlemen above. Any other ideas?

Hey @Tatiana_Wiener! Welcome to the MongoDB Community! We’re lucky to have you here!

Can you post your code and error message in here, so I can better troubleshoot it? Thank you :smiling_face_with_three_hearts:

Hi! Thanks so much for the reply! I have been trying to work through this error for days now! I have working code below (keep in mind I have omitted the username, password, and DB name just for posting purposes)
const {MongoClient} = require(‘mongodb’);

async function main(){
    const uri = "mongodb+srv://{username}:{password}@cluster0.5r4og.mongodb.net/{dbname}?retryWrites=true&w=majority";
 

    const client = await new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true});
 
    try {
        await client.connect();
 
    } catch (e) {
        console.error(e);
    } finally {
        await client.close();
    }
}

main().catch(console.error);

The issue is if I try to call this main function within another function, it does not work. For example: if I had this function plus another React function:

const MongoClient = require('mongodb').MongoClient;    
export default function AboutUsPage(){
      React.useEffect(() => {
        window.scrollTo(0, 0);
        document.body.scrollTop = 0;
      });
      const classes = useStyles();
      main().catch(console.error)

This does not work. I get the error:
TypeError: Cannot read property ‘replace’ of undefined
at matchesParentDomain (uri_parser.js:24)
at uri_parser.js:67

I have even gone so far as trying:

export default function AboutUsPage(){
  React.useEffect(() => {
    window.scrollTo(0, 0);
    document.body.scrollTop = 0;
  });
  const classes = useStyles();
  const uri = "mongodb+srv://{Username}:{Password}@cluster0.5r4og.mongodb.net/{DB}?retryWrites=true&w=majority";
  const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true});
  connect().catch(console.error);
  
  async function connect() {
    await client.connect();

  }

This still does not work! I have no idea what I could possibly be doing wrong.

1 Like

@Tatiana_Wiener - Thank you so much for the additional information and context - it’s so helpful! :smiling_face_with_three_hearts:

Looks to me to be an async issue. You are calling a MongoDB methods before you have connected to the MongoDB cluster in your main method. It’s not shown in your code where you are actually invoking the replace method, but this function is being called too soon. You need to make sure this gets invoked after connecting to your MongoDB cluster. Do you have a link to the GitHub repo or could you show me where/how you are invoking the replace method? My gut is telling me that’s where the issue most likely lives.

Again, thank you so much for posting! I hope we can get this problem sorted out soon! :heart: