FindOneAndUpdate 正在更新变量,但不是数据库

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

我正在创建一个应用程序,如果用户尚未完成培训,则用户应该完成培训。训练完成后,User 集合的trainingCompleted 字段应从 false 更改为 true。通过这段代码,当console.log(updatedUser)时,结果从false变为true,但是在MongoDB Compass中查看的实际MongoDB数据库并没有改变?

我尝试过仅使用 updateOne,但这也不起作用。我尝试过使用 .save(),但这也没有做任何事情。

const userSchema = new mongoose.Schema({
    email: String,
    username: String,
    password: String,
    trainingComplete: {
        type: Boolean,
        default: false,
    },
    topScore: {
        type: Number,
        default: 0,
    },
});

const User = mongoose.model("User", userSchema);


app.put("/users/:username", async (req, res) => {
    try {

        let { username } = req.params;
        console.log(username);
        let updatedUser = await User.findOneAndUpdate(
           { username: username },
           { $set: { trainingComplete: true } }, // Update trainingComplete to true
            { new: true },
        );
        //await updatedUser.save();
        console.log("UpdatedUser:", updatedUser);
        if (!updatedUser) {
            return res.status(404).json({ message: "User not found" });
        }
        res.json({ message: "Training status updated successfully", updatedUser });
        console.log("Updated Successfully");
    } catch (error) {
        console.error("Error updating training status: ", error);
        res.status(500).json({ error: "Internal Server Error" });
    }
});

const handleConfirm = async () => {
        try {
            let userRating = Math.max(selectedRating);
            console.log("UserRating", userRating);

            const response = await fetch(`http://192.168.0.189:3000/patients/${patientID}`);

            if (response.ok) {
                const { patientData, maxNumber } = await response.json();
                console.log("Patient Data:", patientData);
                console.log("Maximum Number:", maxNumber);

              if (userRating === maxNumber) {
                console.log("Correct");
                setRatingCorrect(true);
                const username = await AsyncStorage.getItem("username");
                console.log("Username", username);
                // Update the trainingComplete field for the logged-in user
                await fetch(`http://192.168.0.189:3000/users/${username}`, {
                    method: "put",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({ trainingComplete: true }),
                });
                navigation.navigate("Profile");
                } else {
                    console.log("Incorrect");
                    setRatingCorrect(false);
                }

                setConfirmPressed(true);
            } else {
                console.error("Failed to fetch patient data:", response.statusText);
            }
        } catch (error) {
            console.error("Error updating lesion_GS:", error);
        }
    };`
javascript mongodb mongoose
1个回答
0
投票

您发送更新 MongoDB 数据库中的 TrainingComplete 字段的请求的方式可能存在问题。在您的提取请求中,您将发送带有 keytrainingComplete 的 JSON 正文,但在服务器代码中,您尝试使用 $set: {trainingComplete: true} 更新该字段。这可能会导致更新失败。

请参考此代码:

 await fetch(`http://192.168.0.189:3000/users/${username}`, {
        method: "put",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({}), // Empty body since you are not sending any specific data
    });

在您的服务器代码中,您可以保持 $set 不变:

let updatedUser = await User.findOneAndUpdate(
    { username: username },
    { $set: { trainingComplete: true } },
    { new: true },
);

尝试进行此调整,看看是否可以解决问题,另外,您可以检查服务器的响应,看看是否有任何错误消息或更新是否成功。您可以像这样在前端代码中记录响应:

const response = await fetch(`http://192.168.0.189:3000/users/${username}`, {
    method: "put",
    headers: {
        "Content-Type": "application/json",
    },
    body: JSON.stringify({}),
});

if (response.ok) {
    const data = await response.json();
    console.log("Update successful:", data);
} else {
    console.error("Update failed:", response.statusText);
}

这样,您可以获得有关更新过程中可能出现问题的更多信息。

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