简体   繁体   English

从数组中删除 ObjectId - MongoDB、Mongoose

[英]Delete an ObjectId from an Array - MongoDB, Mongoose

I am trying to delete a 'category' document and it's ObjectId that is in an array inside the 'menu' Schema.我正在尝试删除“类别”文档,它是位于“菜单”架构内的数组中的 ObjectId。 The 'menu' Schema looks like this: “菜单”架构如下所示:

categories: [
  {
    type: ObjectId,
    ref: "Category",
  },

it holds the ObjectId i am trying to delete它包含我要删除的 ObjectId

This is the nodejs code from the controller I try to run:这是我尝试运行的 controller 的 nodejs 代码:

    const deletedCat = await Category.findByIdAndRemove(catId, function (err) {
  if (err) console.error(err)
})
const updateMenu = await Menu.findOneAndUpdate(
  { _id: menuId },
  { $pull: { categories: { _id: new ObjectId(catId) } } },
  { new: true }
)

the $pull doesn't change the DB and the ObjectId is still in the Array. $pull 不会更改数据库,并且 ObjectId 仍在数组中。

I also tried without the " new ObjectId "我也试过没有“新的 ObjectId ”

What am I doing wrong?我究竟做错了什么?

Ok, so i just got it to work.好的,所以我刚刚开始工作。 The answer is simple, just use the ObjectId as a value of the key in the Array (name of the array)答案很简单,只要用ObjectId作为Array中key的值(数组名)

const updateMenu = await Menu.findOneAndUpdate(
  { _id: menuId },
  { $pull: { categories: ObjectId(catId) } },
  { new: true }
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM