使用数组更新mongoDB文档

时间:2018-10-18 10:55:45

标签: mongodb

以下是mongoDB集合中名为“ rooms”的文档。我需要将特定的“玩家”状态从false更新为true。

{
"_id": {
    "$oid": "5bc8535236566e061818e83f"
},
"players": [
    {
        "socketId": "Ux3fiSZZcooITDMlAAAB",
        "email": "s@gmail.com",
        "status": false
    }
],
"confirmed": 0,
"ready": 1,
"status": "started",
"size": 1,
"date": {
    "$date": "2018-10-18T09:33:06.125Z"
},
"__v": 0}

我可以按照下面的代码创建一个新文档。但是,将玩家数组修改为从false变为true的相同方法不起作用(room.save()调用不会更新数组。

        const newUser = {
            socketId: socket.id,
            email: data.user.email,
            status:false
        }; 
        const players = [];
        let promise1;
        let size = parseInt(data.user.roomSize);
        Room.findOne({ size:  size, status : 'waiting' }).then((room) => {
            if (room === null) {
                players.push(newUser);
                if(size === 1) {
                    promise1 = new Room({ players, size, status : 'started' }).save();
                } else {
                    promise1 = new Room({ players, size }).save();
                }                    
            } else {
                room.players.forEach(function(player) {
                    players.push(player);
                });                    
                players.push(newUser);
                room.players = players;
                if(players.length === size) {
                    room.status = 'started';
                }
                promise1 = room.save();
            }
            ......
            ......

0 个答案:

没有答案