Operation `todos.insertOne()` buffering timed out after 10000ms --- MongoDB Express Error

49 Views Asked by At

This is a simple todo list I was doing and whenever I run it and reload the page it throws me an error. The code is :

import mongoose from "mongoose"
import express from "express"
import { Todo } from "./models/Todo.js"

let conn = mongoose.connect("mongodb://localhost:27017/todo")
const app = express()
const port = 3000


app.get('/', (req, res) => {
    const todo = new Todo({ title: "First List", desc: "Description of my First List", isDone: false })
    todo.save()
    res.send('Hello World!')
})

app.listen(port, () => {
    console.log(`Example app listening on port http://localhost:${port}`)
})

The error is : MongooseError: Operation `todos.insertOne()` buffering timed out after 10000ms

In case anyone wants to see the TodoSchema :

import mongoose from "mongoose";

const todoSchema = new mongoose.Schema({
    title: String,
    desc: String,
    isDone: Boolean
})

export const Todo = mongoose.model('Todo', todoSchema)

Instead of this what I want to see is a folder called todo gets inserted in my MongoDB Database in localhost with each time I reload the page based on the todoSchema.

2

There are 2 best solutions below

0
We do the best for You On

By default mongoose will buffer commands; this is to manage the possible intermittent disconnections with MongoDB server.

By default, under the event of a disconnection, mongoose will wait for 10 seconds / 10000 milliseconds before throwing an error. This is what happens in your case. Mongoose throws an error after retrying the given insertion command for 10 seconds.

Therefore the main problem is mongoose could not establish server connection in 10 seconds.

This is something to check further. In order to check this connection issue, there needs to be an error handler provided to the connection statement shown below.

let conn = mongoose.connect("mongodb://localhost:27017/todo")

Thanks to @jQueeny, he has given you a code snippet for doing the same. Once you have trapped this error, the error message would help you to know the reason for failing connection.

The hostname - localhost, specified in the connection string has enough potential for this kind of connection issues. You can see the details of a similar case enclosed here. It suggests to replace localhost with IP address.

Why can I connect to Mongo in node using 127.0.0.1, but not localhost?

Thanks

WeDoTheBest4You

0
jQueeny On

Essentially, you are trying to make database queries before you have established a connection.

Ideally you should wait for the connection and catch any errors to see if there are issues when connecting like so:

mongoose.connect("mongodb://localhost:27017/todo")
.then(() => {
   console.log('Connected to MongoDB');
}).catch(err => {
   console.log('Not connected to MongoDB:', err);
})

Then in your route handler you need to adopt an asynchronous approach to making CRUD operations with either then/catch blocks or use the async/await pattern like so:

app.get('/', async (req, res) => { //< mark callback as async
   try{
      const todo = new Todo({ title: "First List", desc: "Description of my First List", isDone: false })
      await todo.save(); //< await the save() method
      res.status(201).json({
         message: 'New Todo Created'
      })
   }catch(err){
      console.log(err);
      res.status(500).json({
         message: 'Error on server'
      })
   }
});