Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Module 67 Web Development

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Module 67 Web Development

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

MongoDB atlas

First go to the mongdb atlas website and create or login account


After creating go to the quick start
Copy the username and password
Start creating project
Like: Simple-simple-server
Code: mkdir simple-curd-server
Cd simple-crud-serever
Npm init –y
Npm i express cors mongodb
[Here we installing express cors and mongobd]
After doing this go to the vs studio there open “package.json” file and in the “test”
section write “strat:”node index.js”,
By doing this we are telling to start our index file for that reason and our main or
entry point is index,js for that reason now we will create a index.js file
Now we go to the index.js file
There: we will require express by making a const expess like this: conse expres =
require(‘express’)
Now we will make a “app” which will call this express like this: const app =
express();
We also require cors in the same way : const cors = require(‘cors’)
Now we need a port so let’s make it : const port= porcess,env.PORT [this line
shows the available port] || 5000 [by this mean if any port is now available then use
5000 port]
Now we need to use middleware which we get in the beginning express and cors
now use this like this: app,use(cors());
App.use(express.json())
Now let’s go to the running process like this;
app.get(‘/’,[this is where we will go], (req,res) => {
res.send(“simple curs is running”)} [then we created a function which send two
parameter which is req, res here we use res ])
after doing this we will do listen thing which will indicate our port like this:
app.listen(port, () => {
console.log(`simple crud is running on ${port}`)
Now run this by doing some code in cmd
Nodemon index.js
After all of this let’s go back to the mongdb thing in the begging we copied pass
and username will past this here for now but in finale or real project can’t do this
Now in this mongodb website in quickstart we will scroll down and select “cloud
environment” after that we will do ip address things where we can give any ip
address to access this server now we will give only any up address can access this
we will do this by doing this work done
After that click Finish and close
Now we will go to network access option from there we will click add ip address
option and there we will find a option allow access from here click this
Here is an option button called database access here we can create new user to use
this data base or change pass form here.
Now we will go to the “database option” from here we will click connect here will
see many option but now we click on “drivers” option after that we will see a page
and in the down we will find “code” we will copy that code. But in this code they
set our use name but didn’t set our password we have to set the password, we will
paste this on “index.js” file
Let’s explain this code:

const { MongoClient, ServerApiVersion } =


require('mongodb');
this line requiring mongoclient, serverApiVersion from ‘mongodb
const uri =
"mongodb+srv://jubayera356:<password>@cluster0.
gkcnt7q.mongodb.net/?
retryWrites=true&w=majority&appName=Cluster0";
there they make a string where mongodb will find out access username and
password here we have to set our password

// Create a MongoClient with a


MongoClientOptions object to set the Stable API
version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});

’There they get that ‘uri’ and steup the client

async function run() {


try {
// Connect the client to the server
(optional starting in v4.7)
await client.connect();
// Send a ping to confirm a successful
connection
await client.db("admin").command({ ping:
1 });
console.log("Pinged your deployment. You
successfully connected to MongoDB!");
} finally {
// Ensures that the client will close when
you finish/error
await client.close();
}
}
run().catch(console.dir);

There they make a async function there is try and final thing where in the try they
connect the client and then done ping things after that in the finally they close the
client
We can remove that client close if we want our server run all the time, in this case
we will remove this
Now if you run this you will see in cmd that your mondb successfully connected
like this thngs…

Now we will do client site work for this in cmd do this code
Copy the code form rect router
npm create vite@latest name-of-your-project -- --template react
# follow prompts
cd <your new project directory>
npm install react-router-dom localforage match-sorter sort-by
npm run dev

setup by following react router tutotrial


Now we will do 3 things
We will send data from client site to server from server we will sent to database
Let’s make a form in app.jsx
Now we will make a function which well sent user like this :
const handleAddUser = event => {
event.preventDefault;
const form = event.target;
const name = form.name.value;
const email = form.email.value;
const user = {name, email}
}
Now we have to make API in the backend for this, for this let’s go to index.js
In index.js we will write code aftet client,connect() in the try {} like this:
Here we did post app.post('/users', async(req, res) here we make a async
function=> {
const user = req.body; here we request for body and set that to user and this
body come from our middleware which we make in the beginning
console.log('new user', user ) then for verify we console log this user
})
Now we have made this API now we have to send this data from client site , now
in the function “handdleAddUser” in the down we have to fetch like this:
fetch('http://localhost:5000/users', here we tell where to set data, after telling that
we have to do this things{
method:"POST", we have to tell this method is post
headers:{
'content-type':'application/json'
},
body: JSON.stringify(user) we are sending that user which we made and we
have to send this as a stirngyfy
})
.then(res => res.json())
.then(data => console.log(data))
After doing this if you send data tbat data will be shown is the cmd
Now let’s send the data to the database
We will go now in the this website :
https://www.mongodb.com/docs/drivers/node/current/fundamentals/crud/
Then select ‘’’usage exaple’ then insert operation then Inset a document from
there we will copy the code and past to down to client.connect() in try like this:
const database = client.db("usersDB");
const userCollection = database.collection("user");
we use this outside not in the post because in feature we will use this in other areas
after doing this we will go to the app,post in here we we do this:
const result = await userCollection.insertOne(user);
res.send(result)

now in the ”app.jsx” function let’s make an if function where if data send to
database then it will give “alert” like this in the handleAdduser function:
if(data,insertedId){
alert(“User added successfully”)here “insertedId” is a id which is automatically
given by mongdb for indiv
idual data which is send to database
from,reset()
}
We done create things from CRUD let’s jump on Read things:
Let’s go to client code there in src folder make a new folder name this Components and make a
file on that Users.jsx
And make route for this jsx on main.jsx and make a loader with a arrow function where we will
fetch like this:
{
Path:’’/users’
Element:<Usert/>,
Loader: () => fetch(‘’)
}
After doing this we have to make a get In the index.js for this users we already made post now
we will make a get upper of post before doing code we have to go to the mongodb doc from ther
in find operations after their find multiple documents
link(https://www.mongodb.com/docs/drivers/node/current/usage-examples/find/) after checking
the doc we will code like this:
app.post("/users", async(req, res) here we make a async function => {
const cursor = userCollection.find(); here we made a variable named this cursor in here
we called userCollection which we made earlier for store our data there after calling
userCollection we use find option bythis in cursor variable our all date will come
const result = await cursor.toArray() here we make a variable named it result here we use
await to come the data after that we call cursor and make this cursor to array by
user ,toArry() because we have to get data in the form of array
res.send(result); here we just simply send result by using res,send
})

Now if we want to see this data we can go to localhose:5000/users


Now we have made this get and now we can see this code then we also can fetch
this code on our <Users/> element let’s do this:

{
path:"/users",
element:<Users/>,
loader: ()
=>fetch('http://localhost:5000/users')

}
Now we will go to the Users.jsx and do some code to show the data in UI
We have to make a variable where we call a function useLoaderData which will
take fetch data from main.jsx
Like this:
Const users = useLoaderData();
After that we will map the users data to take single data and show in UI like this:

{
users.map(user => <p
key={user._id}>{user.name} : {user.email}</p>)
}

So we done create (post) and Read(get) from crud now we will make
Delete things let’s do it:
For doing this we will go to the users.jsx in there we will make a button we every
user for delete purpose like this :
<button>x</button>
After that we have to make a handle where the delete function will work after
making that handle we will use this in the delete button like this:
Const handleDelete = _id (here we make a parameter and name this _id because we make
delete button for every single data and whenever the delete button clicked then that specific data
will be deleted we know every data have a specific _id for similarities we also named this
parameter _id) => {
Console.log(_id)
Fetch(‘http://localhost:5000/users/${_id}”)(here we have fetched the backend link
and toke the specific data by using ${_id}) , {

Method:”DELETE” (We have to tell the method type delete)


}
.then(res => res.json())
.then(data => console.log(data))
}
Now we have to use this on delete button by onclick we know when we are giving
a parameter in a function and using this function in onclick or onsubmit it will
automatically run with out clicking for solving this issue we will set this function
in arrow function like this:
onClick={() => handleDelete(user_id)}
after doing this we have to go to the backend “index.js” and make a “app,delete”
let’s do it” we will do this in the down of pos like thist:
app,post(“/users/:id’)(here we use :id to toke the specific id ) , async(req, res) => {
const id = req.params.id (by using params function we can target specific id)
console.log(‘please delete from database’, id)
const query = {_id : new ObjectId(id)} (now here we make a variable which is qury in here
we have to tell the which this we want to delete from data base and what is that variable name in
here object is: _id and variable is objectId(id) and we use new because this is the mongodb rule)

const result = await userCollection.deleteone(query) (here we make a variable named it


result and here we use our database name and use deleteone function and in the function we put
our query)

res,send(result) (here we send result as a response )


}
Now you will see user is deleted from database but you have to reload the page to
change the UI to fix this problem we will do some code in the user.jsx
In user.jsx we will use UseStatet function and in setUser we will set the reaming
users like this:
Const [user, setUsers] = useState(loaddedUser) (now we changed user to loadedUser)
Now we go the .then(data => {}) this section here we will make a variable which
name will be reaming in this variable we will use filter function to filter out the
deleted user like this:
const remaining = users.filter(user => user._id ! == _id) (here we filtered the user id
which is not matched with deleted id)
setUser(remaining
)
We completed Create(post) Read(Get) Delete and now finally
Update of CRUD:
For do this let’s make an update page and link in the user page in this link we will
make this as dynamic which will be specify by the id like this:
<Link to=”/update/${user_id)}”>btn:Update</Link>
Now let’s setup route and make a component for this
In main.jsx path will be like this:
Path:”/update/:id” (:id this mean this will be go to the specific id )

Element:<Update/>
So for updating any user we have to get the user data for that reason we have to use
loader and fetch the link for fetching the link we have to make API in the backend
Loader: ({params}) => fetch(‘loaclhost:5000/users/${params.id}’) (here destructor
the params and get the id params )

Now let’s make API in the backend , so in this case we have to get specific data
not the hole users let’s do this in the inde.js
App,get(“/user/:id”, asyn(req, res)(here we dynamically set our link by :id)=> {
Const id = req.params.id; (here we speiciy the id which will come by params)
Const query = {_id = new ObjectId(id)} (here we set which object and which data we need
here objecr is _id and data Is ObjecId(id))

Const user = await usersCollection.finOne(query)(here we use findOne function and in


this function we set our querry and it will find only one data)

Res,send(user)

})
Now we will go to the update,jsx
And load the data
Then we will make a form and we will give the defaultvalue which will be loaded
data
Then we will make a handleupdate
Like this:

const loaddedUser = useLoaderData()


const handleUpdate = (event) => {
event.preventDefault;
const form = event.target;
const name = form.name.value;
const email = form.email.value;

<form onSubmit={handleUpdate}>
<input type="text" name="name"
defaultValue={loaddedUser?.name} id="" /><br />
<input type="email"
name="email" defaultValue={loaddedUser?.email}
id="" /><br />
<input type="submit"
value="Update" />
</form>

Now let’s go to the backend and make app which will update our user data :
For this we will use put like this:
App.put(‘/update/:id’, async(req, res) => {
Cons id = req.params.id
Const updatedUser = req.body (here we are requesting the specific update page body )
}
Now we will go to the client site there we have to fetch the link
In the fetch we will dynamic the url and the dynamic part will ne loaddedUser
because from there the data is coming and we will specify by the id like this
Fetch(‘url/loaddedUser._id’) and the nex predecessor is same here is the code:

const loaddedUser = useLoaderData()


const handleUpdate = (event) => {
event.preventDefault;
const form = event.target;
const name = form.name.value;
const email = form.email.value;
const updatedUser = {name, email}
fetch(`http://localhost:5000/users/$
{loaddedUser._id}`, {
method:"PUT",
headers: {
"content-type":
'application/json'
},
body: JSON.stringify(updatedUser)
})
.then(res => res.json())
.then(data => {
console.log(data)
})

Now we are sending data to the server now we will set this data to the database
Now we will go to the app,put here we will make a variable which name will be
filter in this variable we will specify our id
Const filte = {_id: new obejcrId(id)}
After that we create another variable which will be options which will set update
and insert by using this code:
Const options = {upsert true}
After that we will make another variable which will be updatedUser we also made
same name variable which we changed now and named that user
In this variable we will set the value which will be change the code is:
Const updatedUser = {
$set: {
Name:user.name
email:user,email
}
}
After that we will make a final variable which is result where all this variable will
be forced to work
Code:
Consr result = await userColletction.updateOne(filter, updatedUser, option)
Res,send(result)

You might also like