gpt4 book ai didi

javascript - 如何更改 Mongoose 中文档子数组的对象内的 bool 值?

转载 作者:行者123 更新时间:2023-12-02 23:52:28 27 4
gpt4 key购买 nike

我有一个房间模型。其中有一个 User 数组,它有自己的模型。

每个用户都有一堆不同的属性,其中一些是 bool 值。知道特定房间和特定用户的 ID,我尝试更改子数组中特定 User 元素内的 bool 值,如下所示:

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 个参数,第二个是“要返回的可选字段”,这就是您收到错误的原因,mongoose 尝试根据 $set: { mutedAudio: true 选择 select 字段返回} 作为第二个参数传递(因此被视为投影选项)。
使用Model.findOneAndUpdate()它将更新对象作为第二个参数,以及 positional operator $ .

  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 的原始回答 Mongoose find/update subdocument

关于javascript - 如何更改 Mongoose 中文档子数组的对象内的 bool 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55580756/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com