2016-04-07 10 views
4

私のビューでは、ボタンをクリックしてデータベース内のエントリを削除する方法がわかりません。論理はちょうど私に意味をなさない。私の見解は次のようになります。私は、各ボタンが各エントリに接続するために取得するにはどうすればよいボタンでエントリを削除するmongoldb、mongoose、jade、expressを使用してクリックする

enter image description here

?私はあなたがそれを見てスキミングできるように私のビューとルートコードを以下にリストアップします。

ジェイド

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="https://stackoverflow.com/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 

ユーザールート

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

//***potential delete code 

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

      }); 

    }); 

私が言ったようには、私の大きな問題は、特定のエントリを削除するには、ボタンを取得背後にあるだけの論理です。どんな助けでも大いに感謝します。

答えて

3

これを行う1つの方法は、削除するドキュメントのIDを各ボタンに設定することです。

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

とユーザーを削除するには、AJAXリクエストを送信するためにイベントリスナーを追加します。

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}); 
    }); 
}); 
:ノードで

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

をあなたはこのような何かを持っています

関連する問題