How to solve Mongoose v5.11.0 model.find() error: Operation `products.find()` buffering timed out after 10000ms"
Asked Answered
H

27

34

How to solve model.find() function produces "buffering timed out after ... ms"? I'm using mongoose v 5.11.0, npm v6.14.8 and mongodb v

Here's the code.

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const assert = require('assert');

var mongoose = require('mongoose');

try {
    var db = mongoose.connect('mongodb://localhost:27017', {useNewUrlParser: true, dbName: 'swag-shop' });
    console.log('success connection');
}
catch (error) {
    console.log('Error connection: ' + error);
}


var Product = require('./model/product');
var WishList = require('./model/wishlist');

//Allow all requests from all domains & localhost
app.all('/*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods", "POST, GET");
  next();
});

app.get('/product', function(request, response) {

    Product.find({},function(err, products) {
        if (err) {
            response.status(500).send({error: "Could not fetch products. "+ err});
        } else {
            response.send(products);
        }
    });
});

app.listen(3004, function() {
    console.log("Swag Shop API running on port 3004...");
});

The product model:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var product = new Schema({
    title: String,
    price: Number,
    likes: {type: Number, default: 0}
});

module.exports = mongoose.model('Product', product);

Additionally, running the file also produces the following warnings:

D:\Test\swag-shop-api>nodemon server.js
[nodemon] 2.0.6
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
success connection
Swag Shop API running on port 3004...
(node:28596) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received type function ([Function (anonymous)])
    at validateString (internal/validators.js:122:11)
    at Url.parse (url.js:159:3)
    at Object.urlParse [as parse] (url.js:154:13)
    at module.exports (D:\Test\swag-shop-api\node_modules\mongoose\node_modules\mongodb\lib\url_parser.js:15:23)
    at connect (D:\Test\swag-shop-api\node_modules\mongoose\node_modules\mongodb\lib\mongo_client.js:403:16)
    at D:\Test\swag-shop-api\node_modules\mongoose\node_modules\mongodb\lib\mongo_client.js:217:7
    at new Promise (<anonymous>)
    at MongoClient.connect (D:\Test\swag-shop-api\node_modules\mongoose\node_modules\mongodb\lib\mongo_client.js:213:12)
    at D:\Test\swag-shop-api\node_modules\mongoose\lib\connection.js:820:12
    at new Promise (<anonymous>)
    at NativeConnection.Connection.openUri (D:\Test\swag-shop-api\node_modules\mongoose\lib\connection.js:817:19)
    at D:\Test\swag-shop-api\node_modules\mongoose\lib\index.js:345:10
    at D:\Test\swag-shop-api\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:5
    at new Promise (<anonymous>)
    at promiseOrCallback (D:\Test\swag-shop-api\node_modules\mongoose\lib\helpers\promiseOrCallback.js:30:10)
    at Mongoose._promiseOrCallback (D:\Test\swag-shop-api\node_modules\mongoose\lib\index.js:1135:10)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:28596) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:28596) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I tried increasing the bufferTimeoutMS or disabling the bufferCommands but still it won't work.

Hutton answered 1/12, 2020 at 12:24 Comment(0)
A
44

According to Documentation found in this link: https://mongoosejs.com/docs/connections.html#buffering

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.

TL;DR:

Your model is being called before the connection is established. You need to use async/await with connect() or createConnection(); or use .then(), as these functions return promises now from Mongoose 5.

Avina answered 10/1, 2021 at 7:7 Comment(0)
W
10

Well, I encountered the same problem and had very similar code. I got the same error when sending a get request while testing.

Eventually, I found the solution that my localhost DB wasn't running at that moment. Though it's a foolish error, but I had a hard time finding it.

Womenfolk answered 26/1, 2021 at 13:56 Comment(1)
I also had a hard a time finding the error until I saw this answer.Inkerman
H
7

The issue on model.find() error: Operation products.find() buffering timed out after 10000ms" was resolved by removing the node_module folder, *.json files and reinstalling the mongoose module.

The issue on the warnings was resolved by following this instructions https://mongoosejs.com/docs/deprecations.html

Hutton answered 2/12, 2020 at 6:16 Comment(2)
I'm having a similar problem, MongooseError: Operation users.insertOne () buffering timed out after 10000ms Can you give me some advice?Romish
Hi Paul, have you tried following this instructions mongoosejs.com/docs/deprecations.html? Can you also send the sample code having that error and your package.json file?Hutton
L
6

This error poped becuase you are trying to access models before creating the connection with the database

Always link your mongodbconnection file (if you have created) in app.js by

 var mongoose = require('./mongoconnection');

or just keep mongodb connection code in app.js

Labile answered 2/3, 2021 at 18:36 Comment(0)
C
6

just use 127.0.0.1 instead of localhost

mongoose.connect('mongodb://127.0.0.1:27017/myapp');

Or use family:4 in mongoose.connect method like that

mongoose.connect('mongodb://localhost:27017/TESTdb', {
    family:4
})
    .then(() => {
        console.log('FINE');
    })
    .catch(() => {
        console.log("BAD");
    })
Clanton answered 16/4, 2022 at 3:43 Comment(6)
How does this help if I get the error with a real Mongo cluster?Hughmanick
double-check mongoose docs (Migrating from 5.x to 6.x) If you are using mongoose 6 mongoosejs.com/docs/migrating_to_6.htmlClanton
I never upgraded. I was always using mongoose 6. More importantly, localhost and 127.0.0.1 are literally the same thing (assuming you've not edited your OS hosts file)Hughmanick
I'm not a network expert but the localhost is not always 127.0.0.1, and in the mongoose docs literally says " .... try using 127.0.0.1 instead of localhost ", it worked with my Debian 10 mongoosejs.com/docs/connections.htmlClanton
Using an IPv4 address is related to this issue github.com/Automattic/mongoose/issues/10917Hughmanick
mongoose.connect('mongodb://username:password@host:port/database?options...');Xylotomous
S
5

For me was 100% MongoDB Atlas issue. I've created a cluster in Sao Paulo that for some reason wasn't working as expected. I've deleted it, create a new one in AWS / N. Virginia (us-east-1) and everything started working again.

i'm using this function to connect to the db and avoid some warnings

mongoose.connect(
    url,
    { useNewUrlParser: true, useUnifiedTopology: true },
    function (err, res) {
        try {
            console.log('Connected to Database');
        } catch (err) {
            throw err;
        }
    });
Siphon answered 1/4, 2021 at 17:56 Comment(1)
{ useNewUrlParser: true, useUnifiedTopology: true } isn't needed anymoreHughmanick
O
3

You should check if string connection is correct, because in my case I forgot to include the .env file in my proyect. This file contains string connection for my server in digital ocean.

MONGO_URI="mongodb+srv://server:gfhyhfyh.mongo.ondigitalocean.com/db_customers"
Oscar answered 26/11, 2022 at 15:23 Comment(0)
C
2

For me, the issue was node version. I was getting the same error with nodejs version 17. After trying all the suggestions on this thread, stumbled upon this open issue. Tried downgrading node, but that did not work, finally uninstalled node 17 completely and installed node 16 and the problem was solved! You can check your node version on Mac using node --version

Catt answered 8/12, 2021 at 5:10 Comment(1)
In my case, I was importing models from a custom library which has installed the latest mongoose version and I was using these models within older mongoose version in my Node project. Matching both versions (no matter downgrade or upgrade) of mongoose did the trick for me.Gonzalogoo
W
1

I had the same problem.

After a long search I was able to find it.

I created a new user in MongoDB atlas settings. I changed the MongoDB connection value with the new user.

Changing DNS setting to 8.8.8.8 or changing mongodb connection settings to 2.2.12 did not work.

Wondering answered 25/11, 2021 at 19:31 Comment(0)
S
0

In my case my i forgot to import db.config file in server.js file

Samoyed answered 19/2, 2021 at 16:42 Comment(0)
A
0

There has been a change in mongoose v5^ the spaghetti code has been refactored, It now returns a promise that resolves to the mongoose singleton. so you don't have to do this.

// You don't have todo this
mongoose.connect('mongodb://localhost:27017/test').connection.
  on('error', handleErr).
  model('Test', new Schema({ name: String }));

// You can now do this instead

mongoose.connect('mongodb://localhost:27017/test').catch(err);

Check here for references What's new in Mongoose v5^

If this doesn't work for you, you can then change your connection URL > Select your driver and version to v2.2.12 or later

Ambidexterity answered 31/3, 2021 at 13:36 Comment(0)
B
0

First you should check in which port mongodb currently running.

Use this command to check that port

sudo lsof -iTCP -sTCP:LISTEN | grep mongo

If there you find different port rather than 27017, you should change it

Basque answered 29/5, 2021 at 18:41 Comment(0)
M
0

the best way is to put your initialization in a function, connect to db before starting the server. use a combination of async and a condition to check if environment variables are there(incase db url is in env) here is a sample code.

const start = async () => {
    
    if (!process.env.DB_URI) {
        throw new Error('auth DB_URI must be defined');
    }
    try {
        await mongoose.connect(process.env.DB_URI!, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useCreateIndex: true,
        });
        console.log('Server connected to MongoDb!');
    } catch (err) {
        throw new DbConnectionError();
        console.error(err);
    }

    const PORT = process.env.SERVER_PORT;
    app.listen(PORT, () => {
        console.log(`Server is listening on ${PORT}!!!!!!!!!`);
    });
};

start();
Macilroy answered 14/7, 2021 at 13:35 Comment(0)
S
0

I was having this issue only on deployed lambda functions and everything worked fine on my local. The following worked for me.

  1. Delete node_modules folder.
  2. npm install
  3. commit/push the new package-lock.json file
  4. merge / run cicd pipeline / deploy.
Shipload answered 10/8, 2021 at 8:9 Comment(0)
H
0

This means that, mongo connection has not been established like others have mentioned, go through your code and see if perhaps you forgot to create a mongoConnect() function to connect with your atlas URI

Hulbig answered 2/9, 2022 at 1:40 Comment(1)
The question wasn't asking about AtlasHughmanick
G
0

Possible reason why its failing:

 1. DB connection is not getting setup properly: just check if you data base connection is getting setup and there is not any issue.
 2. MongoDB server/local is running: Make sure you are local connection is working properly.

In my case i found my DB connection were unable to setup properly. After i did that setup properly i started getting the response.

Grandpa answered 18/6, 2023 at 15:26 Comment(0)
L
0

I just moved the connection work to the main app file

Lob answered 25/6, 2023 at 2:18 Comment(0)
H
0

I just didn't have my IP Address added to mongoDB.

Hepta answered 14/8, 2023 at 20:23 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Perichondrium
H
0

Mongoose error: Buffering Timed Out After 10000ms | Fixed Without Using ATLAS | its worked for me .Its funny but its going to work my best answer to slove this is reinstall mongodb according to your version (npm install [email protected])

Hermosa answered 29/8, 2023 at 18:55 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Perichondrium
D
0

In my case, I just had to change IP Access settings on MongoDB Atlas from my current IP to 0.0.0.0/0.

heroku logs --tail

MongoDB Atlas Settings

Devest answered 22/9, 2023 at 3:21 Comment(0)
E
0

Adding 0.0.0.0/0 to my IP Address in mongoDB Atlas worked for me

Esteresterase answered 8/10, 2023 at 20:22 Comment(0)
D
0

I just faced the same error. the problem was in my function, i was trying to fetch suppliers while i'm not connecting to mongo. the fix was just calling the function to open a connection to mongo.

Despatch answered 17/10, 2023 at 14:56 Comment(0)
G
0

I had the same issue, i was using pm2, i just restarted the server.js using this command and problem resolved

pm2 restart server.js
Gunsel answered 20/1 at 6:57 Comment(0)
D
0

In my case, even though I had await on my model, my calling order was wrong:

await loadData();
await mongoose.connect(MONGO_URL);

connect was supposed to come first, so correct order is:

await mongoose.connect(MONGO_URL);
await loadData();
Decortication answered 20/2 at 10:29 Comment(0)
S
0

In my case this { Operation users.find() buffering timed out after 10000ms } error occurs due to mongo URI

This error solve with this URI:

MONGO_URI = "mongodb://localhost:27017/next_auth"

First I use this cloud base Uri

# MONGO_URI = "mongodb+srv://<username>:<password>@cluster0.myn1xym.mongodb.net/mydb"
Swats answered 24/6 at 4:36 Comment(0)
B
0

According to the Documentation found in this link:

https://jsmonkey.net/how-to-solve-mongoose-v5-11-0-model-find-error-operation-products-find-buffering-timed-out-after-10000ms/

To defuse this problematic situation in my case, I considered the following steps:

  • Check Your Connection To MongoDB

It is essential to ensure your application successfully connects to the MongoDB database. Network issues may be delaying or preventing the establishment of the Mongo connection.

mongoose.connect('mongodb://localhost:27017/test', {bufferCommands: false});

Setting bufferCommands to false will prevent Mongoose from buffering commands sent to MongoDB.

Brigandine answered 8/7 at 4:22 Comment(0)
S
0

I encountered the same issue with MongoDB Atlas. A warning message on the website (cloud.mongodb.com) indicated that my IP address wasn't added. So, I added it and then restarted the application, and it worked.

Simplism answered 8/7 at 18:30 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Perichondrium

© 2022 - 2024 — McMap. All rights reserved.