Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Random "MongoServerSelectionError", reason : "ReplicaSetNoPrimary" #11228

Closed
ErnestBrandi opened this issue Jan 16, 2022 · 7 comments
Closed
Labels
needs clarification This issue doesn't have enough information to be actionable. Close after 14 days of inactivity

Comments

@ErnestBrandi
Copy link

Do you want to request a feature or report a bug?
A bug

What is the current behavior?
I occasionally get the following error

{
   "errorType":"Runtime.UnhandledPromiseRejection",
   "errorMessage":"MongoServerSelectionError: connection timed out",
   "reason":{
      "errorType":"MongoServerSelectionError",
      "errorMessage":"connection timed out",
      "reason":{
         "type":"ReplicaSetNoPrimary",
         "servers":{
            
         },
         "stale":false,
         "compatible":true,
         "heartbeatFrequencyMS":10000,
         "localThresholdMS":15,
         "setName":"atlas-5kkpk0-shard-0",
         "maxSetVersion":1,
         "maxElectionId":"7fffffff0000000000000016",
         "commonWireVersion":9,
         "logicalSessionTimeoutMinutes":30
      },
      "stack":[
         "MongoServerSelectionError: connection timed out",
         "    at Timeout._onTimeout (/var/task/node_modules/mongodb/lib/sdam/topology.js:330:38)",
         "    at listOnTimeout (internal/timers.js:557:17)",
         "    at processTimers (internal/timers.js:500:7)"
      ]
   }

It seems similar to this issue #11200, but I had that problem before switching from v5 to v6.

I use Next.js hosting on Vercel, so I use Lambda functions. I connect with the script dbConnect from the official Next.js repo with-mongodb-mongoose.

Also, this happens for different endpoints.

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.
NodeJs : 14.x
Mongoose : 6.1.6
MongoDB : Mongoose dependency

@vkarpov15
Copy link
Collaborator

Without more code samples, not really possible for us to try to repro this. Same stack trace as #11200, but the stack trace doesn't help much because we get the same stack trace from just about any MongoDB operation that times out.

One potentially useful bit of info: did you omit the contents of the reason.reason.servers property, or is it empty in your logs?

@vkarpov15 vkarpov15 added the needs clarification This issue doesn't have enough information to be actionable. Close after 14 days of inactivity label Feb 20, 2022
@vkarpov15 vkarpov15 removed this from the 6.2.3 milestone Feb 20, 2022
@ErnestBrandi
Copy link
Author

ErnestBrandi commented Feb 22, 2022

@vkarpov15 nope, the reason.reason.servers field is always empty in my case.

@vkarpov15
Copy link
Collaborator

Can you link me to the "I connect with the script dbConnect from the official Next.js repo with-mongodb-mongoose." that you mentioned?

@ErnestBrandi
Copy link
Author

The file I'm talking about is the following : https://github.com/vercel/next.js/blob/canary/examples/with-mongodb-mongoose/lib/dbConnect.js
I use it as a middleware as follow :

export default async function database(req, res, next) {
  try {
    await dbConnect();
    req.dbClient = cached.conn.connection.getClient();
  } catch (err) {
    throw new Error("Connection to DB problem");
  }
  if (next) next();
}

// nc stands for "next-connect"
const middleware = nc({ onError: errorHandler });
middleware
  .use(database)
  .use(session)
  .use(passport.initialize())
  .use(passport.session());

@vkarpov15 vkarpov15 added this to the 6.2.8 milestone Mar 6, 2022
@vkarpov15 vkarpov15 removed the needs clarification This issue doesn't have enough information to be actionable. Close after 14 days of inactivity label Mar 6, 2022
@vkarpov15
Copy link
Collaborator

Worth noting: based on your comment, you aren't using Mongoose. cached.conn.connection.getClient() returns a MongoDB Node driver MongoClient instance, so req.dbClient is a MongoClient.

We'll take some time to set up an example with Next hosting and see if we can repro this.

@vkarpov15
Copy link
Collaborator

I set up a Vercel GitHub repo and deployed it: https://github.com/vkarpov15/with-mongodb-mongoose-3 , a quick check shows no errors:

image

Without more complete code samples, there isn't really much we can do to repro this. I suggest you:

  1. Take a look at Mongoose's AWS Lambda docs: https://mongoosejs.com/docs/lambda.html
  2. Add some error handling middleware to drill down what might be causing this error using something like the below code
  // Handle errors on save, etc.
  schema.post(/.*/, { document: true, query: false }, function(err, res, next) {
    console.log('Error on document op:', this.$op, this.model.modelName);
    console.log(err);

    next(err);
  });
  // Handle errors on find, findOne, etc.
  schema.post(/.*/, { document: false, query: true }, function(err, res, next) {
    console.log('Error on query:', this.model.modelName, this.op);
    console.log(err);

    next(err);
  });

For example, if I shut down my local MongoDB server before a findOne() starts, the above middleware will print out:

Error on query: Test findOne
MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
    at Timeout._onTimeout (/home/val/Workspace/MongoDB/mongoose/node_modules/mongodb/lib/sdam/topology.js:312:38)
    at listOnTimeout (internal/timers.js:557:17)
    at processTimers (internal/timers.js:500:7) {
  reason: TopologyDescription {
    type: 'Single',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    commonWireVersion: 9,
    logicalSessionTimeoutMinutes: undefined
  }
}

This can at least point you in the direction of where in your code this error is coming from.

@vkarpov15 vkarpov15 removed this from the 6.2.9 milestone Mar 27, 2022
@vkarpov15 vkarpov15 added the needs clarification This issue doesn't have enough information to be actionable. Close after 14 days of inactivity label Mar 27, 2022
@wethinkagile
Copy link

Maybe a network or security group problem?

@Automattic Automattic locked and limited conversation to collaborators Mar 4, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
needs clarification This issue doesn't have enough information to be actionable. Close after 14 days of inactivity
Projects
None yet
Development

No branches or pull requests

3 participants