【问题标题】:Remove object from nested array of objects从嵌套的对象数组中删除对象
【发布时间】:2021-12-28 17:53:10
【问题描述】:

我得到了这个用户架构

const UserSchema = new Schema({
  email: {
    type: String,
    required: true,
    unique: true,
  },
  groups: [
    {
      groupName: {
        type: String,
        required: true,
      },
      groupMembers: [{ type: Schema.Types.ObjectId, ref: "GroupMember" }],
    },
  ],
});

我想根据给定的“userId”和“groupId”从“groups”数组中删除一个组,我的尝试(使用 express 和 mongoose):

router.delete(  
  "/:userId/:groupId",
  catchAsync(async (req, res) => {
    const { userId, groupId } = req.params;
    const updatedUser = await User.findByIdAndUpdate(
      userId,
      { $pull: { "groups.$._id": groupId } },
      { new: true }
    );
    res.send({ updatedUser });
  })
);

请求的响应:我收到一个错误:“位置运算符没有从查询中找到所需的匹配项。”

编辑: 删除组后,我需要删除 groupMembers 数组中的所有组成员。 User集合结构示例:

{
"_id" : "111",
"email" : "michael@gmail.com",
"username" : "michael098",
"groups" : [
    {
        "_id" : "222"
        "groupName" : "family",
        "groupMembers" : [
            {
                "_id" : "333"
                "name" : "Liam"
            },
            {
                "_id" : "444"
                "name" : "Noah"
            }
        ]
    },
    {
        "_id" : "555"
        "groupName" : "friends",
        "groupMembers" : [
            {
                "_id" : "666"
                "name" : "Oliver"
            }
        ]
    }
  ]
}

在每个组内都有组成员,并且我在 UserSchema 中引用了组成员的集合:groupMembers: [{ type: Schema.Types.ObjectId, ref: "GroupMember" }] GroupMember集合结构示例:

{
    {
        "_id" : "333"
        "name" : "Liam"
    },
    {
         "_id" : "444"
         "name" : "Noah"
    },
    {
         "_id" : "666"
         "name" : "Oliver"
    }
 }

例如,当我获得 userId="111" 和 groupId="222" 的参数时,我将从987654330@收藏。

GroupMember删除_id="222"组后的集合:

 {
        {
             "_id" : "666"
             "name" : "Oliver"
        }
  }

【问题讨论】:

  • 架构中的userId 在哪里?
  • userId 是用户的_id

标签: node.js mongodb express mongoose mongodb-query


【解决方案1】:

假设一个实际的文档可能看起来像这样(使用字符串而不是 ObjectId 以使示例更紧凑):

    {_id:1, groups: [ { type: "ID1", ref: "XX" }, { type: "ID2", ref: "G1" }, { type: \
"ID3", ref: "G2" } ] }

那么此更新将删除groups 数组中的子文档,其中_id = 1type = ID2

db.foo.update({_id:1},  
              { $pull: { groups: { type: "ID2" } }}
             );

【讨论】:

  • 谢谢它的工作。现在我有另一个问题-我想删除我刚刚删除的group 中的所有groupMembers,这样做的正确方法是什么?
  • 你能补充一点关于你所寻求的细节吗?像之前和之后的文档?
  • 我编辑了我的问题。希望这现在更容易理解了。
  • $pull 将从groups 数组中删除_id 222 的整个子文档。是否意味着您要转到另一个集合并删除_id222 组?编辑您的问题以显示您希望生成的文档的外观。
  • 这是一个单独的指令,例如db.groupMembers.remove({_id: 222})
猜你喜欢
  • 2020-12-07
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
  • 2019-11-02
  • 2019-04-30
  • 2021-10-29
  • 1970-01-01
  • 2020-04-15
相关资源
最近更新 更多