Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete an array item in meteor using mongo?

I have this app I'm working on...

http://stevedavis.meteor.com/

You can see the contents of the group collection by doing a 'Groups.find()' in the console.

I have this in my JS...

Template.listGroups.events({
  'click .deleteMember': function(){
    var groupID = this.groupID,
        firstName = this.firstName,
        lastName = this.lastName;
  }
});

So, I wanna be able to delete a member from a group if I click the X next to their name. I've tried...

Groups.update( {"_id": groupID }, {$unset: { "members" : {"firstName": firstName, "lastName": lastName} } } );

but it removed ALL members. I only want it to remove the members item that matches the first and last name of the element clicked. Thanks.

like image 554
Steven Avatar asked Apr 24 '13 23:04

Steven


People also ask

How do I remove an element from an array in MongoDB?

To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

How to delete a particular field in MongoDB?

The $unset operator deletes a particular field. Consider the following syntax: { $unset: { <field1>: "", ... } } The specified value in the $unset expression (i.e. "" ) does not impact the operation.

How to use unset in MongoDB?

In MongoDB, the $unset operator is used to delete a particular field. The value specified in the $unset expression does not make any impact on the operation. The $unset has no effect when the field does not exist in the document. name of the column or field to be deleted.


1 Answers

Ah, I just had to change "$unset" to "$pull". I added via "$push" so I thought, "Is there a $pull method?" And there was! :)

Groups.update( {"_id": groupID }, {"$pull": { "members" : {"firstName": firstName, "lastName": lastName} } } );
like image 194
Steven Avatar answered Nov 08 '22 15:11

Steven