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
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
Try to connect with:
Also, no need to call
await user.save()
if you create a new instance withUser.create()
.