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

标签 javascript mongodb mongoose

我有一个房间模型。其中有一个 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/

相关文章:

javascript - 我可以避免在 ng-repeat 循环中使用对象变量名吗?

javascript - 多次生成带有名称标签和 Logo 的二维码

java - 哪些客户端浏览器语言被广泛使用?

c# - 如何在 C# 的 MongoDB 驱动程序中应用软删除过滤器?

mongodb - Mongoose findAndUpdate() 验证器为 null

javascript - ("error"上的 jQuery)在 chrome 中不起作用

c++ - 在 Cygwin 上编译 MongoDB C++ 驱动程序

node.js - 如何在 meteor 中使用 mongo 模式验证和 typescript ?

javascript - Mongoose .geoNear聚合,添加基本查询选项

node.js - 如果未找到 ID,Mongoose 更新文档或插入新文档(Express REST API)