Answer a question

I am new to MongoDB and just encountered two types of connection string.

  1. mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

  2. mongodb+srv://[username:password@]host[/[database][?options]]

I know about the 1st one. But unfamiliar with the (+srv) in the 2nd.

   let connectionUrl;
      if (username && password)
        connectionUrl = `mongodb://${username}:${password}@${host}:${
          port || 27017
        }/${databaseName}`;
      else
        connectionUrl = `mongodb://${host}:${
          port || 27017
        }/${databaseName}`;
      console.log(connectionUrl, "connectionUrlconnectionUrl");
      let connection = await mongoose.createConnection(connectionUrl, {
        useNewUrlParser: true,
      });
      return connection;

Now the problem user can enter username, password, hostname, etc...

But is there any way to know when to add (+srv) because I was trying with localhost and with MongoDB atlas. Atlas works fine with +srv but in the case of localhost, it's throwing an error.

Answers

in MongoDB 3.6 is introduced the concept of a seed list that is specified using DNS records, specifically SRV and TXT records. You will recall from using replica sets with MongoDB that the client must specify at least one replica set member (and may specify several of them) when connecting. This allows a client to connect to a replica set even if one of the nodes that the client specifies is unavailable

You can see an example of this URL on a 2.2.12 or later connection string

enter image description here

Note that without the SRV record configuration we must list several nodes (in the case of Atlas we always include all the cluster members, though this is not required). We also have to specify the ssl and replicaSet options

With the 3.4 or earlier driver, we have to specify all the options on the command line using the MongoDB URI syntax.

The use of SRV records eliminates the requirement for every client to pass in a complete set of state information for the cluster. Instead, a single SRV record identifies all the nodes associated with the cluster (and their port numbers) and an associated TXT record defines the options for the URI.

enter image description here

check the Reference

Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐