Remove item from Array reference (Mongoose)
I have a User model that contains an array of links to other users:
friends : [ { type: Schema.Types.ObjectId, ref: 'User' } ]
How do I remove an item from this list? This is what I am trying to do so far:
var index = user.friends.indexOf(friend_id);
This gets the index of the element correctly. Now I am trying splicing:
user.friends = user.friends.splice(index, 1);
user.save();
Unfortunately this doesn't work. Any advice?
source to share
There is a problem with the way you are using splice()
. You use it and expect to user.friends
be the resulting array. However splice()
, the context actually changes the array and returns the deleted elements. Essentially, it user.friends
now contains deleted items rather than changed items.
To fix this, simply remove the assignment on run splice()
:
user.friends.splice(index, 1);
instead of as it is at the moment:
user.friends = user.friends.splice(index, 1);
source to share