Javascript 如何在Mongoose中更改文档子数组对象内的布尔值?
我有一个房间模型。其中有一个用户的数组,它有自己的模型 每个用户都有一组不同的属性,其中一些是布尔属性。知道特定房间和特定用户的ID后,我尝试更改子数组中特定用户元素内的布尔值,如下所示:Javascript 如何在Mongoose中更改文档子数组对象内的布尔值?,javascript,mongodb,mongoose,Javascript,Mongodb,Mongoose,我有一个房间模型。其中有一个用户的数组,它有自己的模型 每个用户都有一组不同的属性,其中一些是布尔属性。知道特定房间和特定用户的ID后,我尝试更改子数组中特定用户元素内的布尔值,如下所示: Room.findOne({_id: roomId, "users" : user}, { "$set" : { mutedAudio : false}}) .then(doc => { console.log("Unmuted audio");
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 }
有人知道答案吗
多谢各位
编辑:
接受4个参数,第二个是要返回的可选字段,这就是为什么出现错误的原因,mongoose试图根据$set:{mutedAudio:true}选择要返回的字段,该字段作为第二个参数传递,因此被视为投影选项。
使用,它将更新对象作为第二个参数,以及
原文由@Neil Lunn在中给出,谢谢你,Moad。它不再向我抛出错误,控制台日志unmuted audio正常工作,我的套接字发送一条消息,就好像更改成功一样,但是当我检查Mongodb实例中的值时,没有任何更改。react客户端上的Redux状态也未检测到任何更改。您是否有任何可能出错的线索?您是否可以为您的房间和用户提供代码?我已将它们添加到主Post您的查询实际上返回房间文档,您正在尝试在房间文档上设置mutedAudio。看看这个问题
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
}
});
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);
})