Unable to connect with node.js due to "mongodb+srv"; Get error...TypeError: Cannot read property 'replace' of undefined matchesParentDomain

I’m having the EXACT same error as Getting error upon await client.connect() in node.JS and Error with await client.connect() node.JS - #6. I’ve literally spent two days on this issue. To add some more information, I’ve narrowed it down to a node.js parsing issue, specifically related to the “mongodb+srv”. (If I remove the + it gets past the error, but then of course doesn’t connect). Here is where it fails…on node.js code. And I do have the latest node version…

TypeError: Cannot read property 'replace' of undefined
matchesParentDomain
C:/Users/Owner/Dropbox/GitHub/TestChart/node_modules/mongodb/lib/core/uri_parser.js:24
  21 |  */
  22 | function matchesParentDomain(srvAddress, parentDomain) {
  23 |   const regex = /^.*?\./;
> 24 |   const srv = `.${srvAddress.replace(regex, '')}`;
  25 |   const parent = `.${parentDomain.replace(regex, '')}`;
  26 |   return srv.endsWith(parent);
  27 | }

Any thoughts? So frustrating…
Thanks!

Hi @Gregory_Fay,

Could you please try this piece of code and let me know if this works for you?

File: index.js

const MongoClient = require("mongodb").MongoClient;

const uri = "mongodb+srv://readonly:readonly@covid-19.hip2i.mongodb.net/covid19";

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

async function run() {
  try {
    await client.connect();
    const globalAndUS = client.db('covid19').collection("global_and_us");
    const cursor = globalAndUS.find({ country: "France" }).sort(["date", -1]).limit(2);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);

I executed this by just running:

npm install mongodb
node index.js

It’s most probably not the cleanest piece of JS code you will see today as it’s not my main language but I got it to work.

My guess is that you probably need one of these in your MongoClient:

{
  useNewUrlParser: true,
  useUnifiedTopology: true,
}

I hope this helps.
Cheers,
Maxime.

@MaBeuLux88_xxx

I did do a quick test. I already had
useNewUrlParser : true
in there, but just added
useUnifiedTopology : true
to my existing code and that did not help. I’ll try your full code if you still think that’s valuable when I get back in a bit!

Thanks again,
Greg

1 Like

@MaBeuLux88_xxx
Thank you for your reply! I am about to head to a quick lunch but will check the moment I get back. In the meantime, here is the code I am using…

async function getData(coll, loadOptions) { //async

    console.log("DEBUG: At getData()...")

    try {

      const results = await query(coll, loadOptions); //await

      console.log(results);

      //return (results);

    } catch (err) {

      console.log("DEBUG: Query Error!!", err)

      handleError(err, 'Failed to retrieve data');

    }

  }

  const uriMongo = "mongodb+srv://gfay63:PASSWORDHIDDEN@cluster0.vzkfs.mongodb.net/dfs?retryWrites=true&w=majority";

  function goforit() {

    console.log("DEBUG: About to connect... URI: ", uriMongo)

    const clientMongo = new MongoClient(uriMongo, { useNewUrlParser: true });

    clientMongo.connect(err => {

      if (err) {

        console.log("DEBUG: Error Connecting!!!", err);

        console.error(err);

        return;

      }

      console.log("DEBUG: Connected to database!")

      const collection = new clientMongo.database.db("dfs").collection("nba-v3-GamesByDate");

      getData(collection,

        {

          // This is the loadOptions object - pass in any valid parameters

          filter: ["Day", "=", "2021-01-06T00:00:00"],

          sort: [{ selector: "GameID", desc: true }]

        }

      );

    }

    );

  }

@MaBeuLux88_xxx

Could you please try this piece of code and let me know if this works for you?

At this point, I tested your EXACT piece of code (with of course uri/db/collection changed), and the exact same error occurs. I added some debug lines and showed that, as before, this crashes trying to connect…at this line:
await client.connect();
…as an untapped error as described above. From all my previous digging, it is clearly crashing due to the “mongodb+srv” portion of the uri, thus makes sense that this is where it crashed again.

Specifically, traceback shows it is crashing with node.js code, exactly at this line of code from:

./node_modules/mongodb/lib/core/uri_parser.js:24

24 | const srv = .${srvAddress.replace(regex, '')};

FYR, I am on node.js version v14.15.4.

I can’t begin to show how grateful I would be for someone to help resolve this! I have found several other people that have had this EXACT same issue on this Forum as well as others, and no-one has has a Solution yet.

Huge thanks in advance!
Greg

I’m running on Node v14.13.0 and look like npm install mongodb tells me 3.6.3.
Which version of MongoDB are you trying to connect to?

Can you test my piece of code with the same URI I provided? Just to see if you get anything different or can actually execute the query? It points to a public COVID-19 that I have made available in readonly so you can play with it and send some query its way. No worries at all :-).

More info about it here.

By the way, are you able to connect to you cluster with the Mongo Shell from the same PC? I just want to make sure we ruled out all the MongoDB Atlas parameters like user, password and networking issues.

Cheers,
Maxime.

By the way I also saw in your code that you have an extra “database” in your code which is definitely not going to help you: clientMongo.database.db("dfs").

@MaBeuLux88_xxx Thanks for the replies…
It looks like none of my replies are getting approved in a timely manner since I’m new (last night), so not sure what you’ve seen? I replied to your earlier messages several hours ago. Did you see that “At this point, I tested your EXACT piece of code (with of course uri/db/collection changed)” reply yet? It says “Awaiting Approval 2h” for me, but seems like maybe you are seeing it since you’re an employee? :slight_smile:

New replies…

By the way I also saw in your code that you have an extra “database” in your code which is definitely not going to help you: clientMongo.database.db("dfs") .

LOL. Good catch. Just a typo I would have figured out if this ever got there! :wink:

Which version of MongoDB are you trying to connect to?

3.6.3. I am a brand new user so just installed everything last week.

Can you test my piece of code with the same URI I provided?

Yes, I did that, and STILL get the exact same error. :frowning:

By the way, are you able to connect to your cluster with the Mongo Shell from the same PC?

I have been connecting from this same PC via Web, MongoDB Compass, and mongoimport via Powershell perfectly all along. Here is a test via Mongo Shell:

C:\Users\Owner>mongo "mongodb+srv://gfay63:PASSWORDHIDDEN@cluster0.vzkfs.mongodb.net/dfs?retryWrites=true&w=majority"
MongoDB shell version v4.4.3
connecting to: mongodb://cluster0-shard-00-01.vzkfs.mongodb.net:27017,cluster0-shard-00-00.vzkfs.mongodb.net:27017,cluster0-shard-00-02.vzkfs.mongodb.net:27017/dfs?authSource=admin&compressors=disabled&gssapiServiceName=mongodb&replicaSet=atlas-h1a9j7-shard-0&retryWrites=true&ssl=true&w=majority
Implicit session: session { "id" : UUID("10fc15c2-ed60-4c63-ada5-0468ba21819c") }
MongoDB server version: 4.2.11
WARNING: shell and server versions do not match
MongoDB Enterprise atlas-h1a9j7-shard-0:PRIMARY>

LMK what’s next! Much appreciated! :slight_smile:

@MaBeuLux88_xxx

Update: I created a raw, pure, new node application, and the connection works. I have no clue why it doesn’t work in my existing project.

@MaBeuLux88_xxx

Next step: I created a very raw, basic, React App…

npx create-react-app my-app
cd my-app
npm install mongodb
npm start

then inserted your code per the final full code below, and the same parser error occurs. What is going wrong!?

import logo from './logo.svg';
import './App.css';

const MongoClient = require("mongodb").MongoClient;

const uri = "mongodb+srv://readonly:readonly@covid-19.hip2i.mongodb.net/covid19";

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

async function run() {
  try {
    await client.connect();
    const globalAndUS = client.db('covid19').collection("global_and_us");
    const cursor = globalAndUS.find({ country: "France" }).sort(["date", -1]).limit(2);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

And the same error in uri_parser due to “mongodg+srv”…

[HMR] Waiting for update signal from WDS...
TypeError: Cannot read property 'replace' of undefined
    at matchesParentDomain (http://localhost:3000/static/js/0.chunk.js:68308:30)
    at http://localhost:3000/static/js/0.chunk.js:68353:12
    at Object.push../node_modules/node-libs-browser/mock/dns.js.exports.lookup.exports.resolve4.exports.resolve6.exports.resolveCname.exports.resolveMx.exports.resolveNs.exports.resolveTxt.exports.resolveSrv.exports.resolveNaptr.exports.reverse.exports.resolve (http://localhost:3000/static/js/0.chunk.js:85584:5)
    at parseSrvConnectionString (http://localhost:3000/static/js/0.chunk.js:68345:7)
    at parseConnectionString (http://localhost:3000/static/js/0.chunk.js:68847:12)
    at connect (http://localhost:3000/static/js/0.chunk.js:78309:3)
    at http://localhost:3000/static/js/0.chunk.js:76368:5
    at maybePromise (http://localhost:3000/static/js/0.chunk.js:85307:3)
    at MongoClient.push../node_modules/mongodb/lib/mongo_client.js.MongoClient.connect (http://localhost:3000/static/js/0.chunk.js:76365:10)
    at run (http://localhost:3000/static/js/main.chunk.js:190:18)
    at Module.<anonymous> (http://localhost:3000/static/js/main.chunk.js:201:1)
    at Module../src/App.js (http://localhost:3000/static/js/main.chunk.js:331:30)
    at __webpack_require__ (http://localhost:3000/static/js/bundle.js:857:31)
    at fn (http://localhost:3000/static/js/bundle.js:151:20)
    at Module.<anonymous> (http://localhost:3000/static/js/main.chunk.js:444:62)
    at Module../src/index.js (http://localhost:3000/static/js/main.chunk.js:545:30)
    at __webpack_require__ (http://localhost:3000/static/js/bundle.js:857:31)
    at fn (http://localhost:3000/static/js/bundle.js:151:20)
    at Object.1 (http://localhost:3000/static/js/main.chunk.js:681:18)
    at __webpack_require__ (http://localhost:3000/static/js/bundle.js:857:31)
    at checkDeferredModules (http://localhost:3000/static/js/bundle.js:46:23)
    at Array.webpackJsonpCallback [as push] (http://localhost:3000/static/js/bundle.js:33:19)
    at http://localhost:3000/static/js/main.chunk.js:1:65

I am going with MongoDB locally until this can be resolved… :frowning:
Thanks again for your help!

Greg

Ok I just understood what is wrong here and why this will never work :confused:.

What I sent you:

 const MongoClient = require("mongodb").MongoClient;

const uri = "mongodb+srv://user:password@free.abcde.mongodb.net/test?retryWrites=true&w=majority";

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

async function run() {
  try {
    await client.connect();
    const coll = client.db('test').collection('movies');
    const cursor = coll.find();
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);

is back end code.

Copy paste this in a new folder in an index.js file and replace the URI with a valid Atlas URI. Then run

npm install mongodb
node index.js

This will work, because it’s a backend application, executed by Node.js.

What you are trying to do, is use the MongoDB Node.js driver in a front end application which is executed in the browser - so it won’t work. And even if you got it to work, that’s a terrible idea for several reasons.

  • front end code is accessible by your users and can be modified. You can never trust a client. They can retrieve your URI, Atlas user and password and alter the code. It’s not safe at all.
  • If you deploy this application, let’s say it’s a mobile application. It means your data model is now piloted by your mobile applications… Which may never be updated… So if you ever want to change something and alter your data model, you just can’t and you will have to deal all the time with ALL the versions you ever deployed in production in parallel. Nightmares guaranteed.

You need a secure channel between your backend code (Node.js server or Java or Python or whatever you want really) which is a trusted environment which can communicate with your Atlas cluster and your front end code. Usually, people use a REST API or a GraphQL API with some security features like authentification, tokens, TLS, etc.

Basically, you need something between your front end code - which is just your presentation layer - and your database which contains your precious data. This back end layer is where you will implement a few things:

  • user authentification,
  • database access,
  • provide data to the clients (via API),
  • implement the business logic,
  • implement the rules and restrictions (doctors can edit field X but nurse can’t and admins can do anything, etc).

You can choose the traditional path and implement a back end system as I described above, or you can choose the MongoDB Realm path.

All the stuff I described above can be implemented easily in MongoDB Realm and allow your front end application to access safely your MongoDB Atlas cluster.

I implemented a free COVID-19 REST and GraphQL API using MongoDB Realm and I did 2 blog posts to explain how I did:

I hope this helps :slight_smile: !

Cheers,
Maxime.

3 Likes

@MaBeuLux88_xxx
Thank you so much. I was beginning to realize this last night and have been digging into it. This post helps jump start me a bit more, and confirms the issue. That’s what I get for trying to learn too much too fast! :wink: But it all makes complete sense now.

Thank you!
Greg

Enjoy & keep up the good work :smiley: !

Also if you are learning, checkout our MongoDB free courses on MongoDB University. They will teach you the basics of back end. Especially this one might have your interest if you are trying to build a Node.js back end: MongoDB Courses and Trainings | MongoDB University.

Cheers,
Maxime.

1 Like

I’ll definitely go through this course. Thank you. :slight_smile:

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.