I am kinda new to using NodeJS/Express/MongoDB and I am running into an issue when trying to delete an item using the built-in deleteOne Method. When clicking on the trash can icon(fa fa-trash) in my ejs file, I am expecting the item to get deleted but its not actually deleting anything.
Here I have my server-side code using the delete method:
app.delete('/deleteBill', (request, response) => {
db.collection('bills').deleteOne({billName: request.body.billNameS})
.then(result => {
console.log(`bill Deleted`)
response.json('bill Deleted')
})
.catch(error => console.error(error))
})
Here is my client side code that basically makes a fetch to the server side route:
const deleteText = document.querySelectorAll('.fa-trash')
Array.from(deleteText).forEach((element)=>{
element.addEventListener('click', deleteBill)
})
async function deleteBill(){
const bName = this.parentNode.childNodes[1].innerText
try{
const response = await fetch('deleteBill', {
method: 'delete',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
'billNameS': bName
})
})
const data = await response.json()//this response came from the server
location.reload()
console.log(data)
console.log(`bName is: ${bName} .`)
}catch(err){
console.log(err)
}
}
and here is my ejs code:
<!-- Looping through bills -->
<% for (let i = 0; i < info.length; i++) {%>
<%
const billName = info[i].billName
const capitalizedBillName = billName.charAt(0).toUpperCase() + billName.slice(1)
%>
<section class="billBox billCard w-50">
<div>
<h2>Name of Bill</h2>
<h3><%= capitalizedBillName %></h3>
</div>
<div>
<h2>Amount Due</h2>
<h3><%= `$` + info[i].billCost %></h3>
</div>
<div>
<h2>Due Date</h2>
<h3><%= info[i].billDue %></h3>
</div>
<div class="modifyBill">
<span class='fa fa-trash'>
</div>
</section>
<% } %>
I think it has something to do with the way I am trying to handle things in the client side javascript but I cannot pinpoint exactly what I am doing wrong. It would be nice to have a different set of eyes look at this. I feel like the way I am trying to delete the item is not standard best practice.