简体   繁体   中英

Remove mongodb documents from a collection by an array of _ids

Using Meteor, I have a collection for Contacts which I list with a checkbox beside each contact.

I want to be able to select multiple checkboxes and then click a button to delete the selected contacts from the Contacts collection.

With the code I have below, the selected _ids show up in an array in the console, but nothing is being deleted and no error is being produced.

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

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

Server JS

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

Thanks

@corvid: I think you can only remove one at a time on the client (by _id )

@serks: you have an extra array level in there, in your method just do:

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

There's also an error in how you're calling the Method, instead of:

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

Simply pass the parameter directly:

Meteor.call('removeSelectedContacts',selectedContacts);

The method is expecting an array, not an object.

Use the $in operator.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM