CRUD API Mongodb
Api.js:
const express=require('express');
const dbConnect=require('./mongodb');
const mongodb=require('mongodb')
const app=express();
app.use(express.json());
app.get('/',async (req, resp)=>{
let data=await dbConnect();
data=await data.find().toArray();
console.log(data)
resp.send({data})
});
app.post('/', async(req, resp)=>{
let data=await dbConnect();
let result=await data.insert(req.body)
resp.send(result)
});
app.put('/', async(req, resp)=>{
let data=await dbConnect();
let result=await data.updateOne(
{name:req.body.name},
{$set:req.body}
)
console.log(req.body)
resp.send({result:"Updated"})
});
app.delete('/:id',async (req, resp)=>{
console.log(req.params.id)
const data=await dbConnect();
const result=await data.deleteOne({_id:new mongodb.ObjectId(req.params.id)})
resp.send(result)
})
app.listen(5000)
-----------------
Mongodb.js:
const {MongoClient}=require('mongodb');
const url='mongodb://localhost:27017';
const database='e-Comm'
const client=new MongoClient(url);
async function dbConnect()
{
let result=await client.connect();
db=result.db(database);
return db.collection('products');
}
module.exports=dbConnect;
Comments
Post a Comment