我得到了這個用戶架構
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陣列中的所有組成員。結構示例:
{
"_id" : "111",
"email" : "[email protected]",
"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"
}
]
}
]
}
例如,當我獲得 userId="111" 和 groupId="222" 的引數時,我將從資料庫中洗掉整個“家庭”組和groupMembers陣列中的整個組成員(利亞姆和諾亞)。
uj5u.com熱心網友回復:
假設一個實際的檔案可能看起來像這樣(使用字串而不是ObjectId讓示例更緊湊):
{_id:1, groups: [ { type: "ID1", ref: "XX" }, { type: "ID2", ref: "G1" }, { type: \
"ID3", ref: "G2" } ] }
那么此更新將洗掉groups陣列中的子檔案,其中_id = 1和type = ID2:
db.foo.update({_id:1},
{ $pull: { groups: { type: "ID2" } }}
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/359502.html
標籤:节点.js MongoDB 表达 猫鼬 mongodb-查询
上一篇:'ErrorRequestHandler<ParamsDictionary,any,any,ParsedQs,Record<string,any>>'.ts
