Clinton
Clinton

Reputation: 483

"Error: MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms",

I'm running MongoDB Atlas on node express and I got this error when I tested with postman.

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');

require('dotenv').config();

const app = express();
const port = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true }
);
const connection = mongoose.connection;
connection.once('open', () => {
  console.log("MongoDB database connection established successfully");
})

const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');

app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);

app.listen(port, () => {
    console.log(`Server is running on port: ${port}`);
});

This is my .env, I'm guessing the problem might be here too, Kindly help:

ATLAS_URI=mongodb+srv://userone:[email protected]/<dbname>?retryWrites=true&w=majority

Upvotes: 23

Views: 81910

Answers (25)

Galiant
Galiant

Reputation: 91

If anyone still facing this issue this setup helped me to resolve it

  mongoose.connect(process.env.MONGODB, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => console.log(`Database connected successfully`))
  .catch((err) => console.log(err));

  mongoose.Promise = global.Promise;

Upvotes: 0

TiiGRUS
TiiGRUS

Reputation: 91

Me helped this:

1. Change url to 127.0.0.1:27017

2. Change the name database in your url connection to MongodDB.

3. Add two options:

useNewUrlParser: true,
useUnifiedTopology: true,

Result:

mongoose.connect('mongodb://127.0.0.1:27017/your_new_name_db', {
   useNewUrlParser: true,
   useUnifiedTopology: true,
});

Upvotes: 0

Asad Hayat
Asad Hayat

Reputation: 1

Creating New database user Worked for me.

Upvotes: 0

ifedapo olarewaju
ifedapo olarewaju

Reputation: 3441

So I faced the same error but for my case, the reason was because I used the mongoose.createConnection(...) method instead of the mongoose.connect(...) method.

The relevant difference between both of them is that, with mongoose.connect, the created connection is automatically linked with your mongoose models when you do mongoose.model('User', userSchema). However, with mongoose.createConnection, you need to link it with your schema directly like so:

import * as mongoose from 'mongoose'
import { userSchema } from '../path/to/your/schema'

const dbURL = 'mongodb://localhost:27017'
const db = mongoose.createConnection(dbURL, {dbName: 'my-db-name'})

export const User = db.model('User', userSchema)

The important bit is that on the last line, we use the created connection instance db to create our model, rather than using mongoose.model directly.

Keep in mind, this solution is only relevant when you use mongoose.createConnection instead of mongoose.connect

Upvotes: 2

Ifeanyi ajakpovi
Ifeanyi ajakpovi

Reputation: 1

I had the same issue, I removed useCreateIndex: true, and used only:

{
  useNewUrlParser: true
}

Upvotes: 0

Emmanuel Owino
Emmanuel Owino

Reputation: 64

I turned off my mobile hotspot and back on and it worked.

Upvotes: -1

Isaiah Tshabalala
Isaiah Tshabalala

Reputation: 1

I experienced the same issue. But my MongoDB is running locally on my machine. I had forgotten to open the connection before sending my query to the database. So, I added the code to open and close the connection, and it worked.

  try{    
   await mongoose.connect(uri);
  // My mongoose database request code
 }
 finally{
   await mongoose.connection.close();
 }    

Upvotes: 0

Conor Stewart
Conor Stewart

Reputation: 109

This error can be caused by typos in user properties. (I was trying to set "Email" instead of what was defined on my user model: "email").

Upvotes: 1

Thorlani
Thorlani

Reputation: 1

I had this similar issue of recent and what I think gave the error was

require('dotenv').config()

Changed it to this

require('dotenv/config')

or

require('dotenv')

after importing the package, below call the config function

dotenv.config()

Upvotes: 0

Mohammed Aliyaan
Mohammed Aliyaan

Reputation: 19

Double-check some of the things listed below.

  1. Check the username in the database and make sure you have used the same username in the application.
  2. Check the password.
  3. Check the URl of the Database (if any letter is different or changed).
  4. Check the network access if your IP is not present in the IP Access list of the network access section. (Add your IP address if not present there or create add a new IP address).

Add a new IP Address by: -> click on ADD IP ADDRESS -> click ALLOW ACCESS FROM ANYWHERE -> click confirm.

  1. Also check, if you are on your company's network and added that IP Address to the IP Access list, you might face the same issue, if so, then try switching to your mobile internet or some other than the company's network.

Now, run the application.

Checking the above-all points and making them correct has fixed the issue for me. Hope the same for you. :)

Upvotes: 0

Max Lav
Max Lav

Reputation: 11

To solve this, I created a function in index.js, where I asynchronically connecting to my Database and then starting the server, because mongoose doesn't wait for db connection it executes everything on spot, for me that was the problem.

async function start() {
  try {
    //Database Connect
    await mongoose.connect(
      process.env.DB_CONNECTION,
      {
        useNewUrlParser: true,
        useUnifiedTopology: true,
      },
      () => {
        console.log("Database Connected");
      }
    );

    app.listen(3000, () => {
      console.log("Server is running on port 3000 ...");
    });
  } catch (error) {
    console.error(error);
  }
}

Upvotes: 0

Wanderi Mwangi
Wanderi Mwangi

Reputation: 99

in this line of code, ATLAS_URI=mongodb+srv://userone:[email protected]/?retryWrites=true&w=majority

make sure you write actual database name without < > symbols. You have to create your database first in Mongo Atlas. enter image description here

Upvotes: 0

Naveen Kala
Naveen Kala

Reputation: 36

In Latest version of mongoose.

we don't require this object.

{ useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false }

But if you are dealing with older versions of mongoose then definetly you need it. Also in your mongodb network address add this address 0.0.0.0/0 in place of your ip address.

Upvotes: 0

webbharti
webbharti

Reputation: 1

"error:MongooseError: Operation users.insertOne() buffering timed out after 10000ms"

mongoose.connect(process.env.MONGO_URL, {
    useNewURLParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
  },6000000)

  .then(console.log("connected to server"))
  .catch((err) => console.log(err));

add time like 6000000 after options

Upvotes: 0

Bluethunder
Bluethunder

Reputation: 1

In Mongoose version 6 and above don't require those

{    useNewUrlParser: true, 
     useUnifiedTopology: true, 
     useCreateIndex: true, 
     useFindAndModify: false
}

so just delete it. And if you still see app crashed - waiting for file changes before starting... just save it one more time and it will work

Upvotes: 0

Harshit Gangwar
Harshit Gangwar

Reputation: 553

I also faced the same error. In my case, the error was coming up because useFindAndModify was set to false in mongoose connection

Code with error

mongoose.connect(dbUrl, { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
    useFindAndModify: false 
}, () => { 
    console.log('connected to database myDb ;)') 
})

Working Code

mongoose.connect(dbUrl, { 
    useNewUrlParser: true, 
    useUnifiedTopology: true
}, () => { 
    console.log('connected to database myDb ;)') 
})

Upvotes: 2

NeNaD
NeNaD

Reputation: 20304

Step 1:

Go to your Atlas account and open your project.

Step 2:

In the left menu, navigate to Network Access section:

enter image description here

Step 3:

Add your IP Address so only you would be able to connect to your cluster. You can also add 0.0.0.0/0 and it will allow access from everywhere.

Upvotes: 3

user_lehar
user_lehar

Reputation: 11

Change your MongoDB database-user password. It should be alphanumeric with no special characters. Nothing worked out for me, but, changing the password did.

Upvotes: 1

Storm Souper
Storm Souper

Reputation: 56

It's kind of late but probably because of this line useCreateIndex: true it's not working. It seems in mongoDB version 5. this is not supported anymore. Rewrite like the answer of manoj_mi5

mongoose
  .connect(process.env.MONGODB_URL, {
      useNewUrlParser: true,
      useUnifiedTopology: true})
  .then(() => console.log("Database connected!"))
  .catch(err => console.log(err));

to check if there are more errors.

Upvotes: 0

ABHISHEK DUBEY
ABHISHEK DUBEY

Reputation: 21

Check if you didn't forgot to set password in connection string.

Upvotes: 2

Intra
Intra

Reputation: 177

Check your Network Access IP list in MongoDB Cloud.You will only be able to connect to your cluster from the list of IP Addresses

Ensure that your IP Address Setting is Active

Upvotes: 2

Wild Bill
Wild Bill

Reputation: 101

If you are seeing this using Typescript ensure you are importing the connect function from mongoose and use that to connect.

import { connect } from "mongoose";

connect(...).then()

Upvotes: 1

Bassey Rhema
Bassey Rhema

Reputation: 194

In my case, I had to go to Atlas, and reset my whitelisted IP to the correct address.

Then I restarted my local server and tried posting again on postman... And it worked!

Upvotes: 17

Sandip Swain
Sandip Swain

Reputation: 433

I was facing the same issue. It is resolved. I think you might have not allowed network access to everyone in Atlas: MongoDB. Do it will resolve the issue.

Upvotes: 4

manoj_mi5
manoj_mi5

Reputation: 61

  1. First replace <dbname> with your actual DB name, if not created, create one.

  2. Then create collection as required on the Atlas UI itself.

  3. In the Network Access, click on ADD IP ADDRESS and select "allow access from anywhere".

  4. Rewrite your code this way:

mongoose 
 .connect(process.env.MONGO_PROD_URI, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,   })   
 .then(() => console.log("Database connected!"))
 .catch(err => console.log(err));
  1. Now your DB should be connected and working fine.

If still not resolved, check this link.

Upvotes: 6

Related Questions