skip to Main Content

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

Answers


  1. There is a common source of confusion.

    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.

    Please refer to the same incident and its solution.

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

    Thanks
    WeDoTheBest4You

    Login or Signup to reply.
  2. 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'
          })
       }
    });
       
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search