const express = require('express');
const app = express();
const { MongoClient, ObjectId } = require('mongodb')
// API for get data start
const url = "mongodb://localhost:27017/";
app.get('/', (req, res) =>{
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("vasu"); // here vasu is database name
dbo.collection("tnl_register").find().toArray(function(err, result) {
if (err) throw err;
console.log(result);
res.send(result);
db.close();
});
});
});
// API for get one record start
app.get('/:id', (req, res) =>{
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("vasu");
const query = {"_id": ObjectId(req.params.id)};
dbo.collection("tnl_register").findOne(query, (err, result) => {
if (err) throw err;
console.log(result);
res.send(result);
db.close();
});
});
});
// API for get one record end
// API for insert one record start
app.post('/', (req, res) =>{
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("vasu"); // here vasu is database name db is returned by callface fucntion and another db is predefined
const query = {name: req.headers.name, email: req.headers.email, mobile: req.headers.mobile };
dbo.collection("tnl_register").insertOne(query, (err, result) => {
if (err) throw err;
console.log(result);
res.send('Inserted ID : '+result.insertedId);
db.close();
});
});
});
// API for insert one record end
// API for delete one record start
app.delete('/:id', (req, res) =>{
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("vasu"); //here vasu is database name and another db is predefined
const query = {_id: ObjectId(req.params.id)};
dbo.collection("tnl_register").deleteOne(query, (err, result) => {
if (err){
res.send('error');
}else{
if(result.deletedCount === 1){
res.send('One record deleted!');
}else{
res.send('not delete!');
}
}
db.close();
});
});
});
// API for delete one record end
// API for update one record start
app.put('/:id', (req, res) =>{
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("vasu"); // here vasu is database name and another db is predefined.
const id = {_id: ObjectId(req.params.id)};
const query = {$set: {name: req.headers.name, email: req.headers.email, mobile: req.headers.mobile }};
dbo.collection("tnl_register").updateOne(query, id, (err, result) => {
if (err){
res.send('error');
}else{
res.send(result);
}
db.close();
});
});
});
// API for update one record end
app.listen(3000)
Comments
Post a Comment