Skip to content

Instantly share code, notes, and snippets.

@Deeks900
Created October 26, 2022 04:39
Show Gist options
  • Save Deeks900/11ede992890ad5f4223c9c7561797920 to your computer and use it in GitHub Desktop.
Save Deeks900/11ede992890ad5f4223c9c7561797920 to your computer and use it in GitHub Desktop.
app.js
const express = require('express');
const { ObjectId } = require('mongodb');
const {connectToDb, getDb} = require('./db');
//Initiate app and middleware
const app = express();
app.use(express.json())
//db connection
let db;
connectToDb((err)=>{
if(!err){
app.listen(3000, ()=>{
console.log("App listening on port 3000");
})
db = getDb()
}
})
//Fetching all the documents in a collection
app.get('/books', (req, res)=>{
//Pagination
//Getting the current page
const page = req.query.p || 0 //if nothing is passed in query params then we will assume it to be first page as 0
const booksPerPage = 1
let books = [];
//Getting refrence to the Books Collection
db.collection('Books')
.find() //cursor toArray forEach
.sort({author:1})
.skip(page*booksPerPage) //skip these many docs from this collection
.limit(booksPerPage)
.forEach(book=> books.push(book))
//forEach is asynchronous
.then(()=>{
res.status(200).json(books)
})
.catch(()=>{
res.status(500).json({error:"Could not fetch the documents"})
})
})
//Fetching a single document from a collection
app.get('/books/:id', (req, res)=>{
if(ObjectId.isValid(req.params.id)){
db.collection('Books')
.findOne({_id:ObjectId(req.params.id)})
.then((doc)=>{
res.status(200).json(doc)
})
.catch(err=>{
res.status(500).json({error:"Could not fetch the document"})
})
}
else{
res.status(500).json({error: "id does not exist"})
}
})
//POST Request
app.post('/books', (req,res)=>{
const book = req.body;
db.collection('Books')
.insertOne(book)
.then(result=>{
res.status(201).json(result)
})
.catch(err=>{
res.status(500).json({err:"Could not add a new document"})
})
})
//Delete Request
app.delete('/books/:id', (req, res)=>{
if(ObjectId.isValid(req.params.id)){
db.collection('Books')
.deleteOne({_id:ObjectId(req.params.id)})
.then((result)=>{
res.status(200).json(result)
})
.catch(err=>{
res.status(500).json({error:"Could not delete the document"})
})
}
else{
res.status(500).json({error: "id does not exist"})
}
})
//Update Request
app.patch('/books/:id', (req, res)=>{
if(ObjectId.isValid(req.params.id)){
db.collection('Books')
.updateOne({_id:ObjectId(req.params.id)}, {$set:req.body})
.then((result)=>{
res.status(200).json(result)
})
.catch(err=>{
res.status(500).json({error:"Could not update the document"})
})
}
else{
res.status(500).json({error: "id does not exist"})
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment