我有一个房间模型。它内部是一个具有自己模型的User's数组。
每个用户都有许多不同的属性,其中一些是布尔值。知道特定房间和特定用户的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
}
});
答案 0 :(得分:1)
here包含4个参数,第二个是“要返回的可选字段”,这就是为什么会出现错误,猫鼬试图select
的字段根据$set: { mutedAudio: true }
返回它将作为第二个参数传递(因此被视为投影选项)。
使用Model.findOne()和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在positional operator $中的原始答案