Error: MongooseError: Operation `tours.insertOne()` buffering timed out after 10000ms at Timeout

My DB connection is successful but whenever I try to save the document this error pops up, I have allowed network access to everyone as well. Here is my code:

const mongoose = require('mongoose');
const dotenv = require('dotenv');
const app = require('./app');

dotenv.config({ path: './config.env' });

const DB = process.env.DATABASE.replace(
  '<PASSWORD>',
  process.env.DATABASE_PASSWORD
);
mongoose
  .connect(DB)
  .then(() => {
    console.log('DB connection successfully');
  })
  .catch(err => console.log(err));

// This schema is like the prototype for models to be drawn according to it
const toursSchema = new mongoose.Schema({
  name: {
    type: String,
    // 1st arguement is the value, 2nd is the error message
    require: [true, 'A tour must have a name'],
    unique: true,
  },
  price: {
    type: Number,
    require: [true, 'A tour must have a price'],
  },
  rating: {
    type: Number,
    default: 4.5,
  },
});

const Tour = mongoose.model('Tour', toursSchema);

const testTour = new Tour({
  name: 'The Forest Hiker',
  price: 300,
});
testTour
  .save()
  .then(doc => {
    console.log(doc);
  })
  .catch(err => {
    console.log('Error: ', err);
  });

const port = 3000 || process.env.PORT;
app.listen(port, () => {
  console.log(`Listening on port ${port}...`);
});

Please help me out I’m stuck with this problem for quite sometime and not able to proceed further.

Hi @dhairya_srivastava .

Welcome to The MongoDB Community Forums! :wave:

How did you check if the connection was successful? Did you get DB connection successfully in the logs?

As per your error, Error: MongooseError: Operation tours.insertOne() buffering timed out after 10, 10 seconds is the default buffer timeout and it generally happens when an operation is being performed without connecting to database.

Additionally, as per this documentation on 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 the issue could be that your model is being called before the connection is established. Please try using async/await with connect() as shown in Error Handling - Mongoosejs.

mongoose.connect('mongodb://localhost:27017/test').
  catch(error => handleError(error));

// Or:
try {
  await mongoose.connect('mongodb://localhost:27017/test');
} catch (error) {
  handleError(error);
}

Regards,
Tarun

4 Likes

Thanks @Tarun_Gaur for your help. The problem is resolved now!!!

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.