meteorBuzz
meteorBuzz

Reputation: 3200

MongoDb remove object elements from an array

I have removed the contents of an element in an array but how can I remove it entirely so the index position disappears. Right now, the index position it was sitting at has the value of null.

enter image description here

How can I remove these null indexes entirely because my html iterates over the array so the index position with null values are still being processed. This is my current update method. I intend to completely remove the element. I query the object by matching the object id.

click event: docId = this.docId

Meteor.users.update({_id: this.userId, 'profile.experiences.docId': docId}, {$unset: {'profile.experiences.$': docId}});

The objects are created in the method as follows:

var expDoc = {
        contents: ' ',
        rank: ' ',
        docId: new Mongo.ObjectID()
    };
    Meteor.users.update({_id:this.userId}, {$addToSet: {'profile.experiences': expDoc}});

Upvotes: 1

Views: 2184

Answers (1)

NoOutlet
NoOutlet

Reputation: 1969

You should be using $pull instead of $unset.

Your update query should look like this:

Meteor.users.update({_id: this.userId}, {$pull: {'profile.experiences': {docId: docId}}});

The $pull performs a search of the given array so you don't have to search for documents which match both the _id and the profile.experiences.docId - you just need to find the _id.

Upvotes: 3

Related Questions