'GENERAL QUESTION - how to delete db object (subdoc) from client side (button or input)?

I'm using ejs and bootstap to loop over a db array of objects and display as a table on the client. I'd like to give users the options to delete rows from the table (eg., subdocs from the db) from the client but am struggling to find the best way to do so.

What I've Tried A lot of the videos I've come across on youtube leverage jQuery to build dynamic tables and I guess store in local memory, but never interact with the server. Because my request would be going to the database, I tried creating a button that sends a POST delete request to the server but I'm struggling to figure out how to indicate which subdoc the button will delete.

Button attempt

   <tbody>
     <% for (let fan of artist.fans){%>
     <tr>
       <th scope="row"><%= artist.fans.findIndex(f=> f.id == fan.id) +1 %></th>
       <td><%= fan.email %></td>
       <td><%= fan.gender %></td>
       <td><%= fan.age %></td>
       <td><%= fan.subscribed %></td>
       <td><%= fan.dateAdded %></td>
       <td style="padding-left: 2rem;">
           <form action="/artists/<%= artist.id%>/fanlist?_method=DELETE" method="POST">
             <button class="btn" value="<%= fan.id %>" style="color:white; border: none; margin: 0px; padding: 0px;"><i class="bi bi-trash" style="color: #00B0F0;"></i></button>
      </td>
      <% } %> 
    </tr>
  </tbody>

When I click the button I receive error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

The button doesn't send any data in the form of a request to the server, so I can't "catch" a req.body.id (for ex) and use that to find and delete the subdocument from the database. Because of this, I tried switching the button to an <input> tag instead but can't get that to work either.

Function

module.exports.deleteFanEmail = async (req, res) => {
    const { id } = req.params;
    const fanId = req.body._id;
    Artist.findOneAndDelete({"_id": id, "fans._id": fanId }, (error, data) => {
        if(error){
            res.send(error);
        } else {
            res.send(data);
            res.redirect('artists/fanlist');
        }
    });
}

DB Model

const artistSchema = new Schema({
image: [ImageSchema], 
genre: [ String ], 
fans: [{ 
    email: String, 
    subscribed: String, 
    gender: String, 
    age: Number 
        dateAdded: {
            type: Date,
            default: Date.now
                }
      }], 
 });    

Help / Ask

I'm not even sure I'm on the right path. Is this is something that should be handled via my route handler through the server or do I need to look into a jQuery solution? If it's the former, do I need an input or does a button work just as well?

I'm new-ish and am not sure what path to take. Thank you!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source