Receiving Timeout error with NodeJS and MongoDB Community 6.0.3 on Windows 10

Hi there, I’ve been trying to deal with this timeout error all day, and I’m not sure what else to do. I have Compass installed as well, and I have no issues in Compass. It’s just the module that has an issue, it seems.

Here’s my code that I use:

// MongoDB
const mongoURI = `mongodb://Admin:${process.env.MONGODB_ADMIN_PW}@localhost:27017/?authMechanism=DEFAULT`;
const { MongoClient } = require('mongodb');
const mongo = new MongoClient(mongoURI);

// ...

// Database stuff
const findLighthouse = async (uname) => {
    try {
        await mongo.connect();

        const db = mongo.db('lighthouses');
        const lighthouses = db.collection('lighthouses');

        const lighthouse = lighthouses.findOne({ "user.username": uname });

        return lighthouse;
    } finally {
        await mongo.close();

// ...

server.get('/lighthouse', async (req, res) => {
    res.render('lighthouse', {
        isLoggedIn: true,
        username: 'DragonOfDojima',
        pageTitle: 'A Lighthouse!',
        lighthouse: await findLighthouse('dragonofdojima')

The user does exist in the collection in the database, I’ve tried it with mongosh. Works fine there. Whenever I try to connect to Mongo via my code, though, I always get a timeout error before it can really do anything. The issue seems to be at await mongo.connect();

I’m currently using MongoDB Community 6.0.3 for the MongoDB server, and version 4.12.0 of the mongodb NPM package. I have no problem connecting to the server via Compass or mongosh. The service is also running fine. I’ve tried everything from changing localhost to to trying to use IPV6 to setting the server selection timeout higher, nothing works. I’m always arriving at a timeout. The environment variable is also there and correct, I’ve tested with a console.log. Any help would be greatly appreciated!

Share the connection string you use with mongosh and Compass.

Share the user profile with mongosh.

Most likely some options are different.

1 Like

Tremendous thanks for your response! I didn’t even realize mongosh was using a different connection string, but it is still odd that the one Compass uses doesn’t work in my code… ah, well. Can’t win em all. Again, thank you!

1 Like