0

When i run mongoose in this code it seems to me as if it doesnt connect to my database in time. It is a local mongodb database and not atlas.

The error: mongooseError: Operation users.insertOne() buffering timed out after 10000 ms

occurs when i do not comment out the insert operation, and i will get logged in my console after a while that it has connected to the database. When it has not been commented out, i do not get the "mongoose has been connected", but just the aforementioned error.

//script.js

const mongoose = require('mongoose')
const User = require("./User")

mongoose.connect("mongodb://localhost/bh_db", 
()=>{
    console.log("mongoose has been connected")
}, e => console.error(e))

const user = new User({name:"Kyle", age: 26})
user.save().then( () =>console.log("User Saved"))
//User.js

const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
    name: String,
    age: Number
})

module.exports = mongoose.model("User", userSchema)

When i comment out the inserting new user it takes a while, but eventually it will connect to bh_db. Does anyone know what is going on and what the solution is?

asdaw1
  • 13
  • 4

1 Answers1

0
// Connect to the MongoDB cluster
    try{
        mongoose.connect(
            "mongodb://0.0.0.0:27017/bh_db",
            { useNewUrlParser: true, useUnifiedTopology: true },
            () => console.log("Mongoose is connected"),
        );
    } catch (e) {
        console.log("could not connect");
    }
    const dbConnection = mongoose.connection;
    dbConnection.on("error", (err) => console.log(`Connection error ${err}`));
    dbConnection.once("open", () => console.log("Connected to DB!"));
  • Hey Muqtadir, i apprecaite you! Sorry that i didnt see your response earlier. it works! Could you go out of your way to explain how this actually works, and why mine bugged? I would like to understand it aswell – asdaw1 Nov 23 '22 at 11:19
  • You were not specifying the port number in your mongodb uri. Your URI: mongodb://localhost/bh_db Recommended: mongodb://localhost:27017/bh_db – Muqtadir Billah Nov 23 '22 at 11:27
  • Please marked as completed/answered if it worked for you – Muqtadir Billah Nov 23 '22 at 11:27