I am getting started with backend and just keep getting the same error.
This is my server.js –>
// Step 1 create a folder backend
// Step 2 npm init -y
// Step 3 open in VS Code
// Step 4 npm i express
// Step 5 create server.js
// Server Instantiate
const express = require("express");
const app = express();
// used to parse req.body in express -> PUT or POST
const bodyParser = require("body-parser");
// Specifically parse JSON data and add it to the req.body object
app.use(bodyParser.json());
// Server started on port 3000
app.listen(3000, () => {
console.log("Server started at port no 3000");
});
// A get request for route '/'
app.get("/", (req, res) => {
res.send("Hello Jee Kaise hai aap");
});
// '/' route sends a response when accessed via GET
// This is a GET request --> app.get()
app.post("/cars", (req, res) => {
const { name, brand } = req.body;
console.log(name);
console.log(brand);
res.send("car submitted successfully");
});
const mongoose = require("mongoose");
mongoose
.connect("mongodb://localhost:27017/newDB", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("connection successful");
})
.catch((error) => {
console.log("error came");
});
Every time I am running this code in my terminal using "node server". I am getting the "error came" as output from .catch block .
Though my Mongodb server and express server is live but still I am unable to get connected with my database .
I am using Mongodb compass by the way. And the mongoose is also installed properly.
Please help me to come out from this error. I tried a lot but never getting "connection successful" as output.
2
Answers
try with node version 16 or which node you have currently
Check MongoDB Server: First, ensure that your MongoDB server is up and running
Check Mongoose Version : Required Latest Version
use below command – npm install mongoose@latest
In your database make sure your network access is Allow access from anywhere
Database > Setting > Network Access
mongodb+srv://:@cluster0.nig2yzc.mongodb.net/?retryWrites=true&w=majority