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.
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.
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