"cannot read property 'replace' of undefined" for mongodb client

871 views Asked by At

I'm attempting to connect to a MongoDB Atlas cluster and am having an issue in my react app. on await client.connect(), I get TypeError: Cannot read property 'replace' of undefined.

I have verified that the connection string works via MongoDB Compass.

My mongo.ts file

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/database?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(); // Fails here
            console.log(client);
        } catch (error) {
            console.error('Failed to connect to MongoDB server');
            throw error;
        }

        const mongoCollection = client.db("database").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 [];
    }
}

package.json dependencies

  "dependencies": {
    "@material-ui/core": "^4.10.1",
    "@material-ui/icons": "^4.9.1",
    "@types/mongodb": "^3.5.26",
    "bootstrap": "^4.5.0",
    "firebase": "^7.19.0",
    "mongodb": "^3.6.0",
    "mongodb-client-encryption": "^1.1.0",
    "node-sass": "^4.14.1",
    "react": "^16.13.1",
    "react-bootstrap": "^1.0.1",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "3.4.3",
    "realm": "^10.0.0-beta.6",
    "require_optional": "^1.0.1",
    "typescript": "^4.0.2"
  },
1

There are 1 answers

0
JHau On BEST ANSWER

I ran into the same error today doing roughly the same thing. After doing some digging I found that this error tends to occur when you try to use a front-end application to execute a backend function which in this case appears to be a NodeJS driver. Therefore, I’m assuming you’re calling the exported function somewhere in your front-end application. This is problematic for a variety of reasons but besides best practices this will never work. My recommendation would be to use REST API, GraphQL, or MongoDB Stitch Browser SDK. I used the ladder and it worked great for me.