FindOneandUpdate方法从数组中删除所有元素,而不仅仅是指定

时间:2019-04-04 12:09:16

标签: mongodb mongoose web-applications

我正在创建从客户端到服务器'/ removeuser'的发布请求。

router.post('/removeuser', (req, res) => {
    let errors;
    const userId = req.body.userId;
    const roomId = req.body.roomId;

    Room.findOneAndUpdate({_id: roomId }, { $pull: { users: { id: userId } }}, {new: true})
    .then(doc => {
        console.log(doc)
        console.log("User removed." + userId)
        res.json({roomId});
    })
    .catch(err => {
        console.log(err + " some error happened")
        return res.status(404).json(errors);
    });

})

我已经在控制台上记录了roomId和userId,它们都存在。它甚至返回成功并发送响应。但是我注意到它没有按预期运行,因为一旦用户离开房间,我注意到所有用户都消失了。用户离开并且用户子数组为空后,我检查了数据库实例。

任何人有什么建议吗?谢谢。

房间架构:

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({
    username: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    avatar: {
        type: String
    },
    date: {
        type: Date,
        default: Date.now
    }
});

3 个答案:

答案 0 :(得分:1)

感谢您的所有回复。

按ID删除项目无效。我的时间很短,因此必须找到其他解决方案。如果有人遇到这个问题,我所做的就是使用整个用户对象本身,并使用它来引用数据库中的那个对象,该对象最终可以正常工作。

 Room.findOneAndUpdate({_id: roomId}, {"$pull" : {"users" : user}})
        .then(doc => {
            console.log("User removed.")
            res.json({roomId});
        })
        .catch(err => {
            console.log(err + " some error happened")
            return res.status(404).json(errors);
    });

答案 1 :(得分:0)

Room.update({_id: roomId }, { $pull: { users: { $elemMatch: { id: userId  } } }}, { multi: false })

使用$ elemMatch将解决您的问题

答案 2 :(得分:0)

您可以使用子文档的remove()方法:

Room.findOne({_id: roomId })
.exec()
.then(doc => {
    doc.users.id(userId).remove();
    doc.save();
    console.log("User removed." + userId)
    res.json({roomId});
})
.catch(err => {
    console.log(err + " some error happened")
    return res.status(404).json(errors);
});