Follow below steps to get started
- Go to MongoDB cloud
- create project with any name
- create a cluster
- Now connect with the compass by copying the string and pasting in compass
- Inside compass create a database( which is your db name) and collection(this is your model name)
create two folders
backend
frontend
In backend,
- npm init -y
- npm install express, mongoose, cors, nodemon, dotenv
- now add this in scripts in package.json "start": "nodemon server.js"
- npm install body-parser
- npm install express-validator
PORT = 3001
URI = "mongodb+srv://username:password@cluster0.sfkjwki.mongodb.net/learn_mern"
URI string will be obtained from Mongodb->cluster->connect->connect with compass....
In server.js add this to use .env
require("dotenv").config()
const port = process.env.PORT
const uri = process.env.URI
Note:
use app.use(express.json());
to avoid destructing problemss...
for running backend use: npm start
If everything is fine and still giving mongodb cannot connect then
Go to Mongodb cloud and
Navigate to Network Access and Add your Current IP address and restart the server
In your MERN application, when you are dealing with asynchronous operations like fetching data from a database (as in your previous question), you typically use .then() and .catch() to handle the asynchronous flow and potential errors. The try and catch blocks are often used for synchronous code or within async functions that use await.
try {
// Code that might throw an error
const result = someFunction();
} catch (error) {
// Handle the error
console.error('An error occurred:', error);
}
someAsyncFunction()
.then((result) => {
// Handle successful result
console.log('Success:', result);
})
.catch((error) => {
// Handle error
console.error('An error occurred:', error);
});
To validate our data going to db
npm i express-validator
Comments
Post a Comment