Delete a record by clicking a button using mongoldb, mongoose, jade and express

So it’s hard for me to understand how to delete a record in my database with the click of a button on my screen. Logic just doesn't make sense to me. My view is as follows:

enter image description here

How to get each button to connect to each record? I have listed my view and route code below so you can skip it.

Jade

  extends ../userLayout
block localStyles
    link(rel='stylesheet', href='/stylesheets/usersPage/users.css')
block content
    .container
        .users.col-md-11.col-xs-12.table-responsive 
            h1 Current Users
            form.form(method="post" action="/users/view")
                table.col-xs-12
                    tr
                        th Name
                        th Username
                        th
                    each user in users 
                        tr
                            td= user.name
                            td= user.username
                            td  
                                button.btn.btn-danger.col-xs-12 X

user route

  router.post('/view', function(req, res, next) {

//***potential delete code

      userSchema.remove({ name: 'reg' }, function (err) {
          if (err) return handleError(err);
          // removed!      

            });

    });

As I said, my big problem is just the logic of getting a button to delete a specific record. Any help would be greatly appreciated.

+4
source share
1 answer

- , .

//jade
td
   button.remove-doc.btn.btn-danger.col-xs-12(data-id="#{user.id)") X

ajax :

<script>
   $('buttons.remove.doc').on('click', function() {
      var userId = $(this).attr('data-id');
      $.ajax({
         method: "POST",
         url: "/users/delete",
         data: {"userId": userId},
         success: function(result) {
            if(/* check if it is ok */) {
                location.reload();
            }
         }
      })
   });
</script>

node - :

app.post('/users/delete', function(req, res, next) {
   var userId = req.body.userId || req.query.userId;

   userSchema.remove({_id: userId}, function(err, res) {
       if (err) { res.json({"err": err}); } else { res.json({success: true});
   });
});
+4

All Articles