首页 > 解决方案 > Mongoose findOneAndUpdate 在更新文档后偶尔会返回 null

问题描述

我正在使用 Socket.IO 来接收事件。我执行以下代码以使用新参与者更新目标。大多数情况下,这很有效,但是,有时即使文档已成功更新,该函数也会返回 null 目标。

  socket.on('joinGroup', function(goalID, userName) {
        if (goalID == null || userName == null) {
            return socket.error("Missing some required field")
        }
        Goal.findOneAndUpdate({_id: goalID, 'participants.userID': {$ne : socket.uid}, 'participants.userName': {$ne : userName}}, {$push: {participants: {userID: socket.uid, userName: userName, streak: 0}}}, {new: true},  (err, goal) => {
                if (err) {
                    return socket.error(error)
                } else {
                    if (goal == null) {
                        //Means something is wrong, don't send
                        console.log("Goal is null")
                        return socket.emit('customError', "Unable to join goal. Please try again.")
                    }
                    else {
                        sendMessage(socket.uid, userName + " joined the goal.", goalID, 'joined', userName, true)
                        return socket.emit('goals', {goals: [goal]})    
                    }
                }
            }).catch(function(error) {
                return console.log(error);
            });;
    });

有谁知道为什么即使在文档成功更新后也会出现目标 == null ?

标签: node.jsmongoosesocket.io

解决方案


推荐阅读