I have a simple CRUD application, using express, mongoose and EJS. In the index.EJS page, I have a table that displays each product with checkboxes on each row, with each checkbox having the _ID of the product. I have a Delete Selected button which calls a function that puts all checked entries into an array, which essentially becomes an array of IDs that I want to delete. I then want to use the deleteMany and $in methods to delete those entries from my database, as shown below:
async function deleteMany() {
const toDelete = []
const checkboxes = document.querySelectorAll('input[type="checkbox"]')
for (let checkbox of checkboxes) {
if (checkbox.checked == true) {
toDelete.push(checkbox.value)
}
}
await Product.deleteMany(
{
_id: {
$in: toDelete
}
}
)
}
The problem is, I can't access my Product model or my database from the index.ejs file. I can only access them through my server side index.JS file. So it seems I would need a way to send a post request back to index.js so I can perform the database functions there. Of course this is how I'm handling all other routes, such as get, delete and puts for a single entry. But I don't know how to do it for an array of multiple entries.
First question: How do you send and parse that array?
Second question: How do I actually submit a post request from within this function? I don't have a form, and trying to do it through a URI makes no sense because instead of having one :id for the params, I have an array of IDs. I wouldn't want them all showing up in the URI. I was thinking I'd have to hack together a hidden form, populate the name field with the array, and then call form.submit() with the function. But that seems very very kludgey.
Apologies in advance if I've expressed something incorrectly or awkwardly, I'm just learning express/mongoose.
This is a very simple and basic task and I strongly recommend you to read express.js documentation. you should add a post router in your server side and make a request using fetch, axios or other libraries and tools. you should do something like this:
In your index.js (server side):
app.post('/deleteMany' ,(req,res) => {
const toDelete = req.body.toDelete
await Product.deleteMany({_id: {$in: toDelete}})
res.send('deleted') // or whatever
})
note: you need to use body-parser in your express app in order to get req.body.
in your ejs file (frontend):
async function deleteMany() {
const toDelete = []
const checkboxes = document.querySelectorAll('input[type="checkbox"]')
for (let checkbox of checkboxes) {
if (checkbox.checked == true) {
toDelete.push(checkbox.value)
}
}
await fetch("server-url/deleteMany", {
method: "POST",
body: JSON.stringify({ toDelete })
})
}