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


Unfortunately this doesn't work. Any advice?


source to share

2 answers

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



You can use a filter method on an object,
I'm not sure about the syntax, but it should be something like:

console.log(filter(Schema.Types.ObjectId, function(friends) {
  return !(user.friends == friend_id);


let me know!



All Articles