[英]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. 使用Meteor,我有一个联系人集合,其中列出了每个联系人旁边的复选框。
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. 使用下面的代码,选定的_ids将显示在控制台的数组中,但不会删除任何内容,也不会产生错误。
contacts.html 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 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 客户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 服务器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
) @corvid:我认为您一次只能在客户端上删除一个(通过_id
)
@serks: you have an extra array level in there, in your method just do: @serks:您在那里有一个额外的数组级别,在您的方法中只需执行以下操作:
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. 使用$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.