【发布时间】: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