Solve "MongooseError: Operation 'x.find()` buffering timed out after 10000ms"
Tags: mongodb, node, javascript
Published: 2021-05-16 06:47:01

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l8bvjiihgaxka07tgaaa.png)
In my case, I had mongo.js file with the following code that I utilized in index.js file.

**mongo.js**
```javascript
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;
};
```

**index.js**
```javascript
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();
				}
			});
	
};
```
But when I tried to execute the function that uses a find() operation on the model it threw the following error.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mda6n9grtvve2me3d4gh.png)
As you can see it threw the buffering timed out error. 

## So what was the error actually?
 
According to the [documentation](https://mongoosejs.com/docs/connections.html#buffering) 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) with connect() or createConnection(). 

**Updated indes.js**
```javascript
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();
				}
			});
	
};
```
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. 
{% link https://dev.to/veroca88/set-up-mongodb-atlas-and-connect-with-node-js-avoid-mongooseerror-operation-x-findone-buffering-timed-out-after-10000ms-5dpi %}

## 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 Arun-kc/novicebot no-readme %}

## 💜 Thank you for reading 💜
## 🌏 Like | Follow | Share 🌏