簡體   English   中英

通過_ids數組從集合中刪除mongodb文檔

[英]Remove mongodb documents from a collection by an array of _ids

使用Meteor,我有一個聯系人集合,其中列出了每個聯系人旁邊的復選框。

我希望能夠選擇多個復選框,然后單擊一個按鈕以從“聯系人”集合中刪除所選的聯系人。

使用下面的代碼,選定的_ids將顯示在控制台的數組中,但不會刪除任何內容,也不會產生錯誤。

contact.html

<template name="contacts">
    <h1>Contacts</h1>
    <ul>
      {{#each contacts}}
        {{> contact}}
      {{/each}}
    </ul>
    <br/>
    <a href="{{pathFor route='create_contact'}}">Create Contact</a>
    <a class="delete-selected" href="">Delete Selected Contacts</a>
</template>

contact.html

<template name="contact">
  <li style="list-style:none;">
    <input id="{{_id}}" type="checkbox" value="{{_id}}" name="contact"/>
    <a href="{{pathFor 'contact.show'}}"><span class="contact">{{firstName}} {{lastName}} <strong>{{company}}</strong></span></a> {{#if contactType}}({{contactType}}){{/if}}
  </li>
</template>

客戶JS

Template.contacts.events = {
  'click .delete-selected': function(e) {
  e.preventDefault();

  var selectedContacts = [];
  $('input[name=contact]:checked').each(function() {
    selectedContacts.push($(this).val());
  });
  Meteor.call('removeSelectedContacts', {selectedContacts: selectedContacts});
}

服務器JS

Meteor.methods({
    removeSelectedContacts: function(selectedContacts) {
        Contacts.remove({_id:{$in:[selectedContacts]}})
        //Contacts.remove({selectedContacts});
        console.log(selectedContacts);
    }
});

謝謝

@corvid:我認為您一次只能在客戶端上刪除一個(通過_id

@serks:您在那里有一個額外的數組級別,在您的方法中只需執行以下操作:

Contacts.remove({ _id: { $in: selectedContacts }});

調用方法的方式也存在錯誤,而不是:

Meteor.call('removeSelectedContacts', {selectedContacts: selectedContacts});

只需直接傳遞參數:

Meteor.call('removeSelectedContacts',selectedContacts);

該方法需要一個數組,而不是對象。

使用$in運算符。

Template.contacts.events({
  'submit #delete-contacts-form': function (e, template) {
    // assumes permissions are set on server appropriately.
    Contacts.remove({
      _id: {
        $in: $(e.target).find('input:checked').map(el => el.val())  // assumes the value of each checkbox is the _id
      }
    });
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM