2

I just upgraded both mongoose and MongoDB to latest versions and converted the mongod instance to a replica set (single node for testing) but now when Node app connects to it I get the MongooseServerSelectionError: connect ECONNREFUSED ::1:27017error, but I don't understand why the type: 'ReplicaSetNoPrimary', as when I connect to it via the shell the prompt is rs0:PRIMARY>. Serching for this error I always see message: 'connect ECONNREFUSED 127.0.0.1:27017',but looks like mongoose is trying to connect to::1:27017`.

Can you see what I'm doing wrong or missing to setup?

Update: I restarted the machine and at first node app connects fine. Then if restart it it start failing to connect.

rs
[nodemon] starting `node server.js`
App executing to port  3000
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017

Error :

App executing to port  3000
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at NativeConnection.Connection.openUri (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/connection.js:797:32)
    at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/index.js:332:10
    at /Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
    at new Promise (<anonymous>)
    at promiseOrCallback (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
    at Mongoose._promiseOrCallback (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/index.js:1158:10)
    at Mongoose.connect (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/mongoose/lib/index.js:331:20)
    at Object.<anonymous> (/Volumes/ProjectsSSD/FixitServer/fixit_server_node/api/src/config/database.js:33:10)
    at Module._compile (node:internal/modules/cjs/loader:1097:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10) {
  reason: TopologyDescription {
    type: 'ReplicaSetNoPrimary',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: 'rs0',
    maxSetVersion: 1,
    maxElectionId: new ObjectId("7fffffff0000000000000004"),
    commonWireVersion: 13,
    logicalSessionTimeoutMinutes: undefined
  }
}

MongoDB is installed via home-brew as a service so it starts with the machine. Since I need to use transactions I converted my instance to a replica set by editing the mongod.conf adding a replication

systemLog:
  destination: file
  path: /usr/local/var/log/mongodb/mongo.log
  logAppend: true
storage:
  dbPath: /usr/local/var/mongodb
net:
  bindIp: 127.0.0.1
replication:
  oplogSizeMB: 128
  replSetName: "rs0"
  enableMajorityReadConcern: true

and connecting to it shows the rs0:PRIMARY> prompt in the shell :

rs0:PRIMARY> rs.status()
{
    "set" : "rs0",
    "date" : ISODate("2021-12-12T08:33:55.844Z"),
    "myState" : 1,
    "term" : NumberLong(4),
    "syncSourceHost" : "",
    "syncSourceId" : -1,
    "heartbeatIntervalMillis" : NumberLong(2000),
    "majorityVoteCount" : 1,
    "writeMajorityCount" : 1,
    "votingMembersCount" : 1,
    "writableVotingMembersCount" : 1,
    "optimes" : {
        "lastCommittedOpTime" : {
            "ts" : Timestamp(1639298030, 1),
            "t" : NumberLong(4)
        },
        "lastCommittedWallTime" : ISODate("2021-12-12T08:33:50.600Z"),
        "readConcernMajorityOpTime" : {
            "ts" : Timestamp(1639298030, 1),
            "t" : NumberLong(4)
        },
        "appliedOpTime" : {
            "ts" : Timestamp(1639298030, 1),
            "t" : NumberLong(4)
        },
        "durableOpTime" : {
            "ts" : Timestamp(1639298030, 1),
            "t" : NumberLong(4)
        },
        "lastAppliedWallTime" : ISODate("2021-12-12T08:33:50.600Z"),
        "lastDurableWallTime" : ISODate("2021-12-12T08:33:50.600Z")
    },
    "lastStableRecoveryTimestamp" : Timestamp(1639297999, 2),
    "electionCandidateMetrics" : {
        "lastElectionReason" : "electionTimeout",
        "lastElectionDate" : ISODate("2021-12-12T07:28:18.023Z"),
        "electionTerm" : NumberLong(4),
        "lastCommittedOpTimeAtElection" : {
            "ts" : Timestamp(0, 0),
            "t" : NumberLong(-1)
        },
        "lastSeenOpTimeAtElection" : {
            "ts" : Timestamp(1639293898, 1),
            "t" : NumberLong(3)
        },
        "numVotesNeeded" : 1,
        "priorityAtElection" : 1,
        "electionTimeoutMillis" : NumberLong(10000),
        "newTermStartDate" : ISODate("2021-12-12T07:28:18.032Z"),
        "wMajorityWriteAvailabilityDate" : ISODate("2021-12-12T07:28:18.037Z")
    },
    "members" : [
        {
            "_id" : 0,
            "name" : "localhost:27017",
            "health" : 1,
            "state" : 1,
            "stateStr" : "PRIMARY",
            "uptime" : 3943,
            "optime" : {
                "ts" : Timestamp(1639298030, 1),
                "t" : NumberLong(4)
            },
            "optimeDate" : ISODate("2021-12-12T08:33:50Z"),
            "syncSourceHost" : "",
            "syncSourceId" : -1,
            "infoMessage" : "",
            "electionTime" : Timestamp(1639294098, 1),
            "electionDate" : ISODate("2021-12-12T07:28:18Z"),
            "configVersion" : 1,
            "configTerm" : 4,
            "self" : true,
            "lastHeartbeatMessage" : ""
        }
    ],
    "ok" : 1,
    "$clusterTime" : {
        "clusterTime" : Timestamp(1639298030, 1),
        "signature" : {
            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
            "keyId" : NumberLong(0)
        }
    },
    "operationTime" : Timestamp(1639298030, 1)
}

then I modified the connection uri and options as:



const {
  MONGO_USERNAME,
  MONGO_PASSWORD,
  MONGO_HOSTNAME,
  MONGO_PORT,
  MONGO_DB,
  REPLICA_SET
} = process.env;

const options = {
  // useNewUrlParser: true,
  // useUnifiedTopology: true,
  // useCreateIndex:true,
  // useFindAndModify: false,
  // reconnectTries: Number.MAX_VALUE,
  // reconnectInterval: 500,
  connectTimeoutMS: 10000,

};
const url = `mongodb://${MONGO_USERNAME}:${MONGO_PASSWORD}@${MONGO_HOSTNAME}:${MONGO_PORT}/${MONGO_DB}?replicaSet=${REPLICA_SET}`;


mongoose.connect(url, options)
  .then(con => {
    console.log('MongoDB is successfully connected. \n\n ');//, con.connections);
  })

  .catch(function (err) {
    console.log(err);
  });

env values:

PORT=3000
MONGO_USERNAME=someName
MONGO_PASSWORD=somePassword

MONGO_HOSTNAME=127.0.0.1
MONGO_PORT=27017
MONGO_DB=fixit
REPLICA_SET=rs0
Vincenzo
  • 5,304
  • 5
  • 38
  • 96
  • 2
    Does this answer your question? [MongooseServerSelectionError: connect ECONNREFUSED ::1:27017 wont get fixed](https://stackoverflow.com/questions/69763130/mongooseserverselectionerror-connect-econnrefused-127017-wont-get-fixed) – Joe Dec 12 '21 at 10:15
  • @Joe yes it was a problem with the conf file, when using `bindIp: 127.0.0.1`it connects at first server start but then after receiving a query an restarting it fails. If instead I use `bindIpAll: true` it connects as expected. Many thanks. – Vincenzo Dec 12 '21 at 16:25

0 Answers0