mongoose 如何在MongoDB中使用对象数组从对象数组中提取?

1l5u6lss  于 2022-11-13  发布在  Go
关注(0)|答案(2)|浏览(163)

我试图从一个对象数组中提取多个对象,然后我发现了这篇文章
Using MongoDB $pull to delete documents within an Array
这是我的模式和我是怎么做的,但是它不起作用

{
        "_id": "61fed9b89763c1c3b886b74f",
        "TeamName": "Hogwarts",
        "TeamImage": "Avatar ",
        "createdAt": "2022-02-05T20:10:32.885Z",
        "updatedAt": "2022-02-05T20:59:51.359Z",
        "__v": 0,
        "TeamMember": [
            {
                "Name": "Ronne",
                "Email": "test4@gmail.com",
                "_id": "61fee1807df64451141f08df"
            },
            {
                "Name": "Kai",
                "Email": "school021195@gmail.com",
                "_id": "61fee1e3fffd0f55ed92caee"
            },
            {
                "Name": "Selina",
                "Email": "test@gmail.com",
                "_id": "61fee1e3fffd0f55ed92caef"
            },
            {
                "Name": "Jessica Wu",
                "Email": "test1@gmail.com",
                "_id": "61fee1e3fffd0f55ed92caf0"
            },
            {
                "Name": "Hormione",
                "Email": "test3@gmail.com",
                "_id": "61fee1807df64451141f08de"
            }
        ]
    },

删除方法

const team = await Team.findOneAndUpdate(
        {_id: TeamId},
        {
          $pull: { TeamMember: [ {Name: "Ronne"  },{ Name : "Hormione"} ] },
        //   $pull: { TeamMember: {$in:[ {Name: "Ronne"  },{ Name : "Hormione"} ]}},
          
        },
        { new: true,multi: true}
      );

我也尝试了$in方法,但是两种方法都不起作用,我错过了什么吗?或者使用MongoDB进行多次拉取的正确方法是什么?
顺便说一句,我正在为我的模式使用Mongoose,我不知道这是否重要。

r55awzrz

r55awzrz1#

尝试使用此方式

const team = await Team.findOneAndUpdate(
        {_id: TeamId},
        {
          $pull: { TeamMember: {Name: {$in: ["Ronne","Hormione"] } } },          
        },
        { new: true,multi: true}
      );

https://mongoplayground.net/p/Sqo83w8YvVU

taor4pac

taor4pac2#

不要在$pull中包含[ ]方括号。它将不起作用

const team = await Team.findOneAndUpdate(
        {_id: TeamId},
        {
          $pull: { TeamMember: {Name: "Ronne} },          
        },
        { new: true,multi: true}
      );

相关问题