Node.js 如何从对象数组中拼接对象?

Node.js 如何从对象数组中拼接对象?,node.js,express,Node.js,Express,问题是我正在为每个用户对象创建一个收藏夹数组。 我对数组执行了插入请求,以添加一些最喜欢的配方。 问题是何时要从数组中删除收藏夹 它总是删除最后一个对象,而不是我想要的确切对象 const recipe = await getRecipes(req.params.id); //gives the recipe object let user = await User.findById(req.user._id); // gives the user object console.lo

问题是我正在为每个用户对象创建一个收藏夹数组。 我对数组执行了插入请求,以添加一些最喜欢的配方。 问题是何时要从数组中删除收藏夹 它总是删除最后一个对象,而不是我想要的确切对象

const recipe = await getRecipes(req.params.id); //gives the recipe object
 let user = await User.findById(req.user._id); // gives the user object
  
  console.log(recipe);
  user.recipes.splice(user.recipes.indexOf(recipe), 1);

  await user.save();
  res.send(user); 

如果要从数组中删除对象,可以使用如下筛选方法:

user.recipes = user.recipes.filter(r => {
    return r !== recipe;
})

问题是,对传递recipe对象的
indexOf
的调用没有在数组中找到元素,因此它返回
-1
。请参见此代码的工作原理:

let x=[{id:1},{id:2},{id:3}]
设obj={id:2}
设i=x.indexOf(obj)
//我是-1,因为obj不在数组中。
//另一个看起来像obj的物体在那里,
//但它们不是同一个物体
console.log(“i=”,i)
//这将删除最后一个,因为使用-1拼接可以做到这一点
x、 拼接(x.indexOf(“d”),1)
console.log(x)
//当数组中有对象时,可以使用`findIndex`
设y=[{id:1},{id:2},{id:3}]
设j=y.findIndex(e=>e.id==obj.id)
console.log(“j=,j)
y、 接头(j,1)

console.log(y)
然后呢?我将得到true或false否?否,您将得到一个新数组,其中包含回调中通过测试的所有项。我如何使用它?我不明白配方对象是mongo对象。使用_id,RecipeTile。。。