### CRUD Operations
CRUD (Create, Read, Update, Delete) is an acronym for ways one can operate on stored data. It refers to operations performed in a database.
There is some HTTP method that is used to operate CRUD operation.
POST Method :
The POST method is used to create subordinate or new resources. When creating a new resource, POST to the parent and the service takes care of associating the new resource with the parent, assigning an ID.
For example,
app.post('/products', async (req, res) => {
const product = req.body;
console.log(product)
const result = await productsCollection.insertOne(product);
res.json(result);
});
GET Method:
The HTTP GET method is used to read a representation of a resource and returns a representation in XML or JSON and an HTTP response code of 200 (OK).
For example,
app.get('/products', async (req, res) => {
const cursor = productsCollection.find({})
const products = await cursor.toArray();
res.json(products);
})
PUT Method:
PUT is used for update capabilities, PUT-ing to a known resource URI with the request body containing the newly-updated representation of the original resource.
For example,
app.put('/users', async (req, res) => {
const user = req.body;
const filter = { email: user.email }
const options = { upsert: true }
const updateDoc = { $set: user }
const result = await usersCollection.updateOne(filter, updateDoc, options)
res.json(result);
});
PATCH Method:
PATCH is used to modify capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource.
For example,
PATCH /user/jthijssen HTTP/1.1
<user>
<firstname>Joshua</firstname>
</user>
DELETE Method:
DELETE is used to delete a resource identified by a URI.
For example,
app.delete('/orders/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) }
const result = await ordersCollection.deleteOne(query);
res.json(result);
})
To operate this operation, you have to must install,
npm i cors
npm i mongodb
npm i express
npm i dotenv
And must update in script object,
like,
"scripts": {
"start": "node index.js",
"start-dev": "nodemon index.js",
"test": "echo \"Error: no test specified\" && exit 1"
}
Top comments (0)