Skip to content

when mongoose.connect() returns an error the connection.readyState is set to 2 (connecting) #9921

Closed
@fraleigh

Description

@fraleigh

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

bug

What is the current behavior?

When mongoose.connect() throws an error, the mongoose.connection.readyState is sometimes 2 (connecting).

If the current behavior is a bug, please provide the steps to reproduce.

const mongoose = require('mongoose');

const dbUri = "mongodb+srv://username:password@badhost.rtiii.mongodb.net/Database"
const dbOptions = {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    retryWrites: true,
    w: 'majority'
};

mongoose.connect(dbUri, dbOptions)
    .then( () =>  {
        console.log("Connected");
    })
    .catch ((err) => {
        console.log(`connect error: ${err.message}`);
        if (mongoose.connection.readyState != 0) {
            console.log(`mongoose.connect returned an error, but ready state is ${mongoose.connection.readyState}`);
        }
    })

Once every 2-3 runs, the following logs are printed

connect error: querySrv ENOTFOUND _mongodb._tcp.badhost.rtiii.mongodb.net
mongoose.connect returned an error, but ready state is 2

The correct runs, just print

connect error: querySrv ENOTFOUND _mongodb._tcp.badhost.rtiii.mongodb.net

What is the expected behavior?

I would expect the ready state to be 0 (disconnected) if mongoose.connect() fails.

This may be related to #8692. The error does not happen with useUnifiedTopology false. However, in the case where mongoose.connect() fails I would expect the readyState to be appropriately set, not to be delayed by the serverSelectionTimeoutMS.

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.

Node 14.15.4
Mongoose 5.11.13
MongoDB - Atlas 4.4.3
I am running the code on OS X 11.2.

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-bugWe've confirmed this is a bug in Mongoose and will fix it.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions