DEV Community

sujon554
sujon554

Posted on

CURD Operations MongoDB with Node

What is the CURD operations?

When we create a project with React as a client site and with NodeJs as a server site, we have to process some operations on the server site with NodeJs. CURD is an acronym that stands for Create, Update, Read, and Delete. According to our needs, We use to get, post, put, delete methods.

_Important Note:

  • NodeJs is a separate or another runtime of JavaScript.
  • NASA, Uber, IBM, Paypal use NodeJs.
  • The V8 engine makes JavaScript fast Just in time (JIT) compile.
  • npm stands for Node Package Manager.
  • MongoDB keeps the data in JSON structure. _
  • Non-blocking: Single-threaded accepts the request and then sends the request to others. The current thread won’t remain blocked with the request.
  • Asynchronous/ Call back: NodeJs does not work synchronously or one by one.

get any data from mongodb with node.js

Use a database collection by
const productcollection = database.collection('product');
Then, use app.get() function by below system
app.get('/product', async (req, res) => {
const getdata = productcollection.find({});
const showdata = await getdata.toArray();
res.send(showdata);
})
Enter fullscreen mode Exit fullscreen mode

get any single data from mongodb with node.js

Use a database collection by
const productcollection = database.collection('product');
Then, use app.get() function by below system,
app.get('/product/:id', async (req, res) => {
const id = req.params.id;
const getId = { _id: ObjectId(id) };
const showId = await productcollection.findOne(getId);
res.json(showId);
})
Enter fullscreen mode Exit fullscreen mode

Post any data to mongodb with node.js

Use a database collection by
const productcollection = database.collection('product');
Then, use app.post() function by below system

app.post('/product', async (req, res) => {
const add = req.body;
const result = await productcollection.insertOne(add);
console.log(result);
res.json(result);
})
Enter fullscreen mode Exit fullscreen mode

delete any data from mongodb with node.js

Use a database collection by
const productcollection = database.collection('product');
Then, use app.delete() function by below system

app.delete('/product/:id', async(req, res)=>{
const id = req.params.id;
const getId = {_id: ObjectId(id)};
const deleteId = await productcollection.deleteOne(getId);
res.json(deleteId);
})

Enter fullscreen mode Exit fullscreen mode

Top comments (0)