0% found this document useful (0 votes)
62 views6 pages

Lab 1

The document provides instructions for setting up a Node.js application to build a CRUD API connected to a MongoDB database in 10 steps. It then describes adding additional functionality like connecting to MongoDB, creating a user model and controller, building routes to get, create, and read all users, and editing a user record. The steps include initializing the project, installing dependencies, setting up the server, routing, and controllers to manage the CRUD operations for a user collection in the MongoDB database.

Uploaded by

hatemzomor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views6 pages

Lab 1

The document provides instructions for setting up a Node.js application to build a CRUD API connected to a MongoDB database in 10 steps. It then describes adding additional functionality like connecting to MongoDB, creating a user model and controller, building routes to get, create, and read all users, and editing a user record. The steps include initializing the project, installing dependencies, setting up the server, routing, and controllers to manage the CRUD operations for a user collection in the MongoDB database.

Uploaded by

hatemzomor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Fall 2023

Advanced Full Stack Web Programming


Lab 1 - Setting up NodeJS App

A. Create new project folder (same as Step 1 and 2)


1- mkdir crud-API
2- cd crud-API
3- npm init -y
4- npm install mongoose express dotenv cors nodemon
5- create new file index.js
const express = require("express");
const PORT = 8000;
const app = express();
app.listen(PORT, async () => {
console.log(`server up on port ${PORT}`);
});
6- package.json (under scripts “,”)
"start": "nodemon index.js"
7- npm run start (in terminal of index.js)
8- router.js
const router = require("express").Router();
router.get("/", (req, res) => {
res.send("Let's build a CRUD API!");
});
module.exports = router;
9- Open index.js file add the routing object
const router = require("./router");
app.use(router); (at the end of the file)

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

const mongoose = require("mongoose");


const dotenv = require("dotenv");
dotenv.config();

------------------------------------------------------------------------------
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

Create Model for Mongo


1- Create Model
const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({


first_name: {
type: String,
required: true,
},
last_name: {
type: String,
required: true,
},
user_name: {
type: String,
required: true,
},
email: {
type: String,
},
password: {
type: String,
required: true,
},
createdAt: {
type: Date,
default: Date.now,
},
});

module.exports = mongoose.model("User", UserSchema);

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

Build Create API


1- Add post to router
router.post("/users", createUser);
2- Adjust import
const {getUsers,createUser}= require("./Controllers/User");
3- Add Api to controller
const createUser = async (req, res) => {
const user = new User({
first_name: req.body.first_name,
last_name: req.body.last_name,
user_name: req.body.user_name,
email: req.body.email,
password: req.body.password,
createdAt: req.body.createdAt,
});

try {
const savedUser = await user.save();
res.json(savedUser);
} catch (err) {
res.send(err);
}
};
4- Export function
module.exports = {
getUsers,
createUser,
};

5- Add cors to index.js


const cors = require("cors");
app.use(cors());

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

Create Read All


const getUsers = (req, res) => {
User.find()
.then(users => res.json(users))
.catch(err => res.send(err));
};

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

You might also like