DEV Community

Cover image for Solve "MongooseError: Operation 'x.find()` buffering timed out after 10000ms"
Arun K C
Arun K C

Posted on

Solve "MongooseError: Operation 'x.find()` buffering timed out after 10000ms"

This error ate me out for at most 2 days. When I first saw this error I was like, Whhaaattt?? 😵 The connection was ok since the console said so. Or was it?

The problem I faced

When I tried connecting to mongodb it didn't through any error as you can see.
image
In my case, I had mongo.js file with the following code that I utilized in index.js file.

mongo.js

const mongoose = require('mongoose');
require('dotenv').config();

module.exports = async () => {
    await mongoose.connect(process.env.MONGOPATH, {
        keepAlive: true,
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false,
    })
        .then(x => {
            console.log(
                `Connected to Mongo! Database name: "${x.connections[0].name}"`,
            );
        })
        .catch(err => {
            console.error('Error connecting to mongo', err);
        });
    return mongoose;
};
Enter fullscreen mode Exit fullscreen mode

index.js

const mongo = require('../mongo');

module.exports = async (arg1, arg2, arg3) => {

            await mongo().then(mongoose => {
                try{
                    console.log('Connected to mongo!!');
                    command.execute(client, message, args);
                }
                finally{
                    mongoose.connection.close();
                }
            });

};
Enter fullscreen mode Exit fullscreen mode

But when I tried to execute the function that uses a find() operation on the model it threw the following error.
image
As you can see it threw the buffering timed out error.

So what was the error actually?

According to the documentation of mongoose:

Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB.

That's because mongoose buffers model function calls internally. This buffering is convenient, but also a common source of confusion. Mongoose will not throw any errors by default if you use a model without connecting.

So that means we are trying to call the model without even establishing a connection with the database.
(Yea that was the problem)

So how to solve this??

That's simple (yea I know, so simple that it made me crazy for 2 days 😵), we need to use async/await with connect() or createConnection().

Updated indes.js

const mongo = require('../mongo');

module.exports = async (arg1, arg2, arg3) => {

            await mongo().then(async mongoose => {
                try{
                    console.log('Connected to mongo!!');
                    await command.execute(client, message, args);
                }
                finally{
                    mongoose.connection.close();
                }
            });

};
Enter fullscreen mode Exit fullscreen mode

As you can see the only change I had to do was to utilize async/await in this code.

Here the function that utilizes the model will be called into this code via command.execute(). Since we are turning in the arrow function into an async function and using await so that command.execute() runs first, we won't face the buffer problem anymore.

How to connect MongoDB Atlas with your Node.js driver?

For setting up MongoDB Atlas and connecting with Node.js, you could check out this article.

Conclusion

During development we will all face problems like this, be it big or small, share it with others. If this article could at least help one of you and save your time, then the objective of this article is fulfilled.

Note: If you wanna check out the project in which I faced this problem, here is the link, contributions are welcome ❤️

GitHub logo Arun-kc / novicebot

⚔️ A fun-oriented discord bot made using DiscordJS, NodeJS, and MongoDB

💜 Thank you for reading 💜

🌏 Like | Follow | Share 🌏

Top comments (6)

Collapse
 
nawazish12 profile image
Nawazish12

i'm also getting the same error after deployment on heroku when i try to login or signup and on my system app is working properly but after deployment on heroku the error is generating while on login or signup

Collapse
 
arunkc profile image
Arun K C

So the code is working for you locally but once deployed its throwing the error? That's strange 🤔

Collapse
 
domster4444 profile image
Kshitiz

I logged in to this site just to thank you , You saved my 2 day.. Thanks It worked

Collapse
 
arunkc profile image
Arun K C

Thanks for your kind words 😊 Glad to hear that this was helpful to you 😃
@domster4444

Collapse
 
oscarjvd profile image
Óscar Javier Vargas Díaz

What is await command.execute(client, message, args);?

Collapse
 
arunkc profile image
Arun K C

That's just usual await operator

command.execute(client, message, args) is just project specific. I just gave it as an example. It could be anything like await sample_function()