skip to Main Content

Whenever i run my application. I get an error after a few seconds. MongooseError: Operation users.insertOne() buffering timed out after 10000ms

Here is the code i used to connect to the database

const mongoose = require("mongoose");
const express = require("express")
const app = express()


app.use(express.static("views"))
app.use(express.json())
app.use(express.urlencoded({ extended: true }))


mongoose.set("strictQuery", false);
mongoose.connect("mongodb://localhost/newsletter", { useNewUrlParser: true });

const User = require("./User");
// app.use(User)


app.post("/addUser", (req, res, next) => {
    console.log("reqeuest recieved")
    console.log(req.body)

    const name = req.body.name;
    const email = req.body.email;
    saveUser(name, email)

    // Make the user go to the database here
    res.redirect("/")
    next()
})

app.post("/getEmails", (req, res, next) => {
    res.end("im getting emails")
    next()
})

async function saveUser(name, email) { 
    // before adding to the database, see if it already exists
    // if (await User.findOne( { name: name } )){
    //     console.log("not adding to the database")
    //     return;
    // }
    console.log("req recieved")
    const user = await User.create({
        name: name,
        email: email
    })
    await user.save()
    console.log(user);
}

app.listen(3000, () => {
    console.log("Listening")
})```

I called in the scheema after i connected to the databse. I tried using the link that you get from typing mongosh in a command prompt. That works but i want to use the loacl host.

2

Answers


  1. You have to specify port in

    mongoose.connect("mongodb://localhost/newsletter", { useNewUrlParser: true });

    like :

    mongoose.connect("mongodb://localhost:27017/newsletter", { useNewUrlParser: true });

    Your client is not connected to the database probabely

    Login or Signup to reply.
  2. Try to connect with:

    mongoose
      .connect('mongodb://127.0.0.1:27017/newsletter', { useNewUrlParser: true })
      .catch((e) => {
        console.log(e);
        process.exit(0);
      });
    

    Also, no need to call await user.save() if you create a new instance with User.create().

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search