Follow the Following Steps (For Windows)
- windows + R
Enter Cmd
Opens the command prompt/terminal
For Linux & Mac Please follow the guide from Mongodb https://www.mongodb.com/docs/mongodb-shell/run-commands/
type mongosh
show databases
use merndb
show collections
db.users.find()
dont worry about these datas we can insert them later its just for the purpose of the particular command used in the mongo shell
Now lets start coding
Make sure to create your project in this manner
We Only need 4 javascript files to make this work server.js,.env,userRoute.js,userModel.js
/////////////////////////SCRIPT JS///////////////////////////////
const express = require("express");
const app = express();
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const cors = require("cors");
dotenv.config();
app.use(cors());
const userDataRoute = require("./Routes/userRoute");
app.use(express.json());
//Connect to mongodb database(locally)
mongoose
.connect(process.env.URI)
.then(() => {
console.log("Connected Successfully");
app.listen(process.env.PORT || 3000, (err) => {
if (err) console.log(err);
console.log(`running at port ${process.env.PORT}`);
});
})
.catch((error) => console.log("Failed to connect", error));
app.use(userDataRoute);
/////////////////////////.env//////////////////////////////
PORT = 3000
URI = mongodb://127.0.0.1:27017/merndb
////////////////////////userRoute js///////////////////////
const express = require("express");
const mongoose = require("mongoose");
const User = require("../models/userModel"); // Adjust the path as needed
const router = express.Router();
// Create
router.post("/", async (req, res) => {
const { name, email, age } = req.body;
try {
const userData = await User.create({
name,
email,
age,
});
res.status(201).json(userData);
} catch (error) {
if (error.name === 'ValidationError') {
// Mongoose validation error
const validationErrors = Object.values(error.errors).map((err) => err.message);
res.status(400).json({ error: 'Validation failed', details: validationErrors });
} else {
console.error(error);
res.status(500).json({ error: 'Internal server error' });
}
}
});
// Get
router.get("/", async (req, res) => {
try {
const showAll = await User.find();
// Your code to retrieve data from MongoDB or perform other operations
res.status(200).json(showAll);
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
});
//Get Single User
router.get("/:id", async (req, res) => {
const {id} = req.params;
try {
const singleUser = await User.findById({_id : id});
// Your code to retrieve data from MongoDB or perform other operations
res.status(200).json(singleUser);
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
});
//Delete
router.delete("/:id", async (req, res) => {
const {id} = req.params;
try {
const singleUser = await User.findByIdAndDelete({_id : id});
// Your code to retrieve data from MongoDB or perform other operations
res.status(200).json(singleUser);
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
});
// Update
router.patch("/:id", async (req, res) => {
const { id } = req.params;
const { name, email, age } = req.body;
try {
const updatedUser = await User.findByIdAndUpdate(
id,
{ name, email, age },
{ new: true }
);
// Check if the user with the specified ID exists
if (!updatedUser) {
return res.status(404).json({ error: "User not found" });
}
// Your code to retrieve data from MongoDB or perform other operations
res.status(200).json(updatedUser);
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
});
module.exports = router;
//////////////////////////userModel js///////////////////////
const mongoose = require("mongoose");
//create scehma
const userScehma = new mongoose.Schema({
name:{
type: String,
required: true
},
email : {
type: String,
unique: true,
required: true,
},
age : {
type: Number,
required: false,
},
},
{ timestamps: true }
);
//create Model
const User = mongoose.model('User', userScehma)
module.exports = User;