Javascripter
Javascripter

Reputation: 145

Deleting an entry through a button click using mongoldb, mongoose, jade and express

So I am having trouble figuring out how to delete an entry in my database by a button click in my view. The logic just isn't making sense to me. My view looks like this:

enter image description here

How do I get each button to connect to each entry?? I'll list my view and route code below so you can skim through 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!      

            });

    });

Like I said, my big issue is just the logic behind getting a button to delete a certain entry. Any help would be GREATLY appreciated.

Upvotes: 4

Views: 6847

Answers (1)

Alexandru Olaru
Alexandru Olaru

Reputation: 7092

One way to do this is to set in the each button an id of the document that you want to remove.

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

and add an event listener to send an ajax request to delete the user:

<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>

in node you will have something like this:

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});
   });
});

Upvotes: 5

Related Questions