如何在Mongoose中更改文档子数组的对象中的布尔值?

问题描述 投票:0回答:1

我有房型。其中包含一个具有自己模型的User数组。

每个用户都有一堆不同的属性,其中一些是布尔值。知道特定房间的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
    }
});
javascript mongodb mongoose
1个回答
1
投票

Model.findOne()有4个参数,第二个是“可选字段返回”,这就是你得到错误的原因,mongoose试图根据select返回$set: { mutedAudio: true }字段,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); })

Mongoose find/update subdocument

@Neil Lunn在qazxswpoi的原始回答

© www.soinside.com 2019 - 2024. All rights reserved.