我有一个房间模型。其中有一个用户数组,它有自己的模型。
每个用户都有一堆不同的属性,其中一些是布尔属性。知道特定房间和特定用户的 ID,我正在尝试更改子数组中特定 User 元素中的布尔值,如下所示:
Room.findOne({_id: roomId, "users" : user}, { "$set" : { mutedAudio : false}})
.then(doc => {
console.log("Unmuted audio");
res.json(doc)
io.in(roomId).emit('userchange');
})
.catch(err => {
console.log(err);
})
(我使用用户模型而不是用户 ID 在子数组中查找用户。无法使ID工作,但可以通过将其与自身完全进行比较来获取对象。
我收到错误:
MongoError: Unsupported projection option: $set: { mutedAudio: true }
有人知道这个问题的答案吗?
谢谢。
编辑:
const RoomSchema = new Schema({
owner: {
id: {
type: String
},
username: {
type: String
}
},
roomname: {
type: String,
required: true
},
category: {
type: String,
required: true
},
password: {
type: String,
required: false
},
users: [UserSchema],
messages: [{
username: {
type: String
},
message: {
type: String
},
time: {
type: String
}
}],
date: {
type: Date,
default: Date.now
}
});
const UserSchema = new Schema({
id: {
type: String
},
username: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
avatar: {
type: String
},
date: {
type: Date,
default: Date.now
},
micEnabled: {
type: Boolean,
default: false
},
mutedAudio: {
type: Boolean,
default: true
}
});
Model.findOne(( 需要 4 个参数,第二个是"要返回的可选字段",这就是您收到错误的原因,猫鼬试图根据作为第二个参数传递的$set: { mutedAudio: true }
select
字段返回(因此被认为是投影选项(。
使用 Model.findOneAndUpdate((,它将更新对象作为第二个参数,以及位置运算符 $。
Room.findOneAndUpdate(
{ "_id": roomId, "users._id": userID },{ "$set": { "users.$.mutedAudio": false } } )
.then(doc => {
console.log("Unmuted audio");
res.json(doc)
io.in(roomId).emit('userchange');
})
.catch(err => {
console.log(err);
})
@Neil Lunn 在猫鼬查找/更新子文档中的原始答案