从参考数组中删除项目(猫鼬)

opt*_*con 4 javascript mongodb node.js

我有一个 User 模型,其中包含对其他用户的引用数组:

friends          : [ { type: Schema.Types.ObjectId, ref: 'User' } ]
Run Code Online (Sandbox Code Playgroud)

如何从此列表中删除项目?这是我到目前为止正在尝试的:

var index = user.friends.indexOf(friend_id);
Run Code Online (Sandbox Code Playgroud)

这正确地获取了项目的索引。现在我正在尝试拼接:

user.friends = user.friends.splice(index, 1);
user.save();
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不起作用。有什么建议吗?

boo*_*box 6

你使用的方式有问题splice()。您正在使用它并期望user.friends成为结果数组。但是,splice()实际上更改上下文数组并返回已删除的项目。所以基本上,user.friends现在保存删除的项目而不是修改的项目。

要解决此问题,只需在执行时删除分配splice()

user.friends.splice(index, 1);

而不是你目前拥有它的方式:

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