我正在尝试通过猫鼬查询MongoDB数据库以更新数据库的许多字段。我想第一个请求是正确的,因为猫鼬不会触发任何错误,但对于嵌套架构,我收到以下错误。
我的目标是删除 userTag 在朋友中的出现次数,并删除 friendRequestsSent 当 userTarget 等于 userTag 时发送,当用户请求等于 userTag 时删除 friendRequestsReceived 以及当数据等于 userTag 时的通知。
以下是我的模型的架构
const NotificationSchema = new Schema({
title: String,
type: Number,
icon: String,
data: String,
createdAt: { type: Date, default: Date.now },
})
const FriendRequestSchema = new Schema({
userRequest: { type: String, required: true },
userTarget: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
})
const UserSchema = new Schema({
tag: { type: String, required: true, unique: true },
friendRequestsSent: { type: [FriendRequestSchema] },
friendRequestsReceived: { type: [FriendRequestSchema] },
friends: { type: [String] },
notifications: { type: [NotificationSchema] },
})
请求
const updateResponse = await User.updateMany(
{
friends: { $elemMatch: { $eq: userTag } },
friendRequestsSent: {
userTarget: {
$elemMatch: { $eq: userTag },
},
},
friendRequestsReceived: {
userRequest: {
$elemMatch: { $eq: userTag },
},
},
notifications: {
data: {
$elemMatch: { $eq: userTag },
},
},
},
{
$pull: {
friends: userTag,
friendRequestsSent: { userTarget: userTag },
friendRequestsReceived: { userRequest: userTag },
notifications: { data: userTag },
},
}
)
错误
Error while deleting the user account: Cast to String failed for value "{ '$elemMatch': { '$eq': '0eQzaAwpt' } }" at path "userRequest" for model "User"
friendRequestsReceived
中的userRequest
字段是类型String
,而不是数组,因此$elemMatch
不起作用。此外,您不需要使用$elemMatch
,因为您在$elemMatch
表达式中只指定了一个条件,如文档中所述:
如果在$elemMatch表达式中仅指定单个条件,则无需使用 $elemMatch。
在您的情况下,您只需要执行以下操作(详细信息在这里(:
await User.updateMany({
friends: userTag,
"friendRequestsSent.userTarget" : userTag,
"friendRequestsReceived.userRequest": userTag,
"notifications.data": userTag
}...