最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove item from reference Array (Mongoose) - Stack Overflow

programmeradmin0浏览0评论

I have a User model that holds an array of references to other users:

friends          : [ { type: Schema.Types.ObjectId, ref: 'User' } ]

How can I remove an item from this list? This is what I'm trying so far:

var index = user.friends.indexOf(friend_id);

This properly gets the index of the item. Now I'm trying a splice:

user.friends = user.friends.splice(index, 1);
user.save();

Unfortunately this isn't working. Any advice?

I have a User model that holds an array of references to other users:

friends          : [ { type: Schema.Types.ObjectId, ref: 'User' } ]

How can I remove an item from this list? This is what I'm trying so far:

var index = user.friends.indexOf(friend_id);

This properly gets the index of the item. Now I'm trying a splice:

user.friends = user.friends.splice(index, 1);
user.save();

Unfortunately this isn't working. Any advice?

Share Improve this question asked Apr 23, 2015 at 20:56 opticonopticon 3,6145 gold badges40 silver badges67 bronze badges 1
  • This should work, did u check if friend_id really is in that array ? – Jakub Martyčák Commented Apr 23, 2015 at 21:01
Add a ment  | 

2 Answers 2

Reset to default 7

There is an issue with the way you're using splice(). You are using it and expecting user.friends to be the resulting array. However, splice() actually changes the context array and returns the deleted items. So essentially, user.friends now holds the deleted items rather than the modified items.

To fix this, just remove the assignment when you perform splice():

user.friends.splice(index, 1);

instead of how you have it currently:

user.friends = user.friends.splice(index, 1);

You could use the filter method on 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 !!

发布评论

评论列表(0)

  1. 暂无评论