Lab 1
Lab 1
10- http://localhost:8000/
pg. 1 https://blog.avneesh.tech/building-a-crud-api-with-nodejs-and-mongodb
Fall 2023
B. Connect to MongoDB
1- Create Project
2- Create User and password (remember it well!)
Example:
raghdaessam1
R123456
3- Click Network access – Add new IP address – allow access from any IP
4- Click connect to Database
5- Click Drivers – Copy connection (Next time you will choose Resume only)
6- Create new .env file
7- Make a new variable and Copy connection string in .env and replace your password
8- Open Index.js file, create and configure .env database connection
------------------------------------------------------------------------------
mongoose
.connect(process.env.MONGODB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected to MongoDB");
})
.catch((err) => {
console.log(err);
});
pg. 2 https://blog.avneesh.tech/building-a-crud-api-with-nodejs-and-mongodb
Fall 2023
2- Create Controller
const getUsers = (req, res) => {
res.send("I am the get users route");
};
module.exports = {
getUsers,
};
a. Router.js
const {getUsers}= require("./Controllers/User");
router.get("/users", getUsers);
3- http://localhost:8000/users
pg. 3 https://blog.avneesh.tech/building-a-crud-api-with-nodejs-and-mongodb
Fall 2023
try {
const savedUser = await user.save();
res.json(savedUser);
} catch (err) {
res.send(err);
}
};
4- Export function
module.exports = {
getUsers,
createUser,
};
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
6- Open Postman
{
"first_name": "Raghda",
"last_name": "Ali",
"user_name": "raghda_ali",
"email": "[email protected]",
"password": "1234567"
}
pg. 4 https://blog.avneesh.tech/building-a-crud-api-with-nodejs-and-mongodb
Fall 2023
pg. 5 https://blog.avneesh.tech/building-a-crud-api-with-nodejs-and-mongodb
Fall 2023
Edit User
1- Add to Router.js
pg. 6 https://blog.avneesh.tech/building-a-crud-api-with-nodejs-and-mongodb