簡體   English   中英

如何使用 findOneAndUpdate 更新 mongoDB 中的用戶? 拋出內部服務器錯誤 500

[英]how to update a user in mongoDB using findOneAndUpdate? Throwing internal server error 500

好的,所以我目前正在編寫一個 API,當被調用時,應該使用請求中傳遞的數據更新 mongoDB 中的當前用戶。

但是,當我調用 findOneAndUpdate() 時,出現 500 內部服務器錯誤。 (我將在下面展示我嘗試使其工作的幾種方法)

當我調用 findOne() 時,它會毫無問題地找到並返回正確的用戶。 但是后來我遇到了無法更新用戶的問題,我嘗試了 user.name = request.body.name; 其次是 user.save(); 但這沒有用。 所以我決定再次嘗試 findOneAndUpdate。

到目前為止,這是我嘗試過的幾種方法

app.post("/account/edit", auth, (request, response) => {
    User.findOneAndUpdate({email: request.user.userEmail}, {name: request.body.name, email: request.body.email})
        .then((user) => {
            response.send(user)
        })
        .catch((error) => {
            response.status(404).send({
                message: "User not found",
                error,
            });
        })
    }
)

或者原來我有

//edit my account endpoint
app.post("/account/edit", auth, (request, response) => {
    const filter = {email: request.user.userEmail}
    const {name, email} = request.body
    const update = {name:{name}, email:{email}}
    User.findOneAndUpdate(filter, update)
        .then((result) => {
            response.send(result)
        })
        .catch((error) => {
            response.status(404).send({
                message: "User not found",
                error,
            });
        })
    }
)

這兩個都返回 500 個錯誤。 我究竟做錯了什么?

這是我調用 API 的地方,EditProfileForm.js

import React, {useEffect, useState} from 'react';
import axios from 'axios';
import Cookies from "universal-cookie";
const cookies = new Cookies();
const token = cookies.get("TOKEN");

function EditProfileForm() {

    const [ user, setUser ] = useState({name:"", email:""});

    const saveChanges = (e) => {
        e.preventDefault();
        const name = user.name;
        const email = user.email;
        const configuration = {
            method: "post",
            url: "https://MYURL/account/edit",
            headers: {
                Authorization: `Bearer ${token}`,
            },
            data: {
                name,
                email,
            }
        };
        axios(configuration)
            .then((result) => {
                console.log(result);
            })
            .catch((error) => {
                error = new Error();
            })
    }

    // useEffect executes once the page loads 
    useEffect(() => {
        // set configuration for API call
        const configuration = {
            method: "get",
            url: "MYURL/account",
            headers: {
                Authorization: `Bearer ${token}`,
            },
        };
        axios(configuration)
            .then((result) => {
                //assign the User to the in result to User we initialized
                setUser(result.data);
            })
            .catch((error) => {
                error = new Error();
                window.location.href="/";
            });
    }, []);

    return(
    <div className="edit-account">
        <form className="edit-profile-form">
            <ul>
                <li>
                    <p className="edit-form-tag">Name:</p>
                    <input 
                        className="edit-form-input" 
                        id="edit-name"
                        value={user.name || ''}
                        onChange={(e) => setUser({...user, name: e.target.value})}
                    />
                </li>
                <li>
                    <p className="edit-form-tag">Email:</p>
                    <input 
                        className="edit-form-input" 
                        id="edit-email"
                        value={user.email || ''}
                        onChange={(e) => setUser({...user, email: e.target.value})}
                    />
                </li>
                <li>
                <button type="submit" onClick={(e) => saveChanges(e)}>Save Changes</button>
                </li>
            </ul>
        </form>
    </div>
    );
}

export default EditProfileForm;

另外,如果有任何方法可以改進我的問題,請告訴我。 我仍在尋找最佳實踐,並努力讓每個問題都比上一個更清楚。

在嘗試下面的代碼之前,您可以檢查用戶架構中的 email 是否唯一。 如果它是唯一的,並且您傳遞的是 email,它已經存在於數據庫中,它不會修改數據。


app.post("/account/edit", auth, async (request, response) => {
    try{
        let user = await User.updateOne({email : request.user.userEmail}, {
            $set : {"name" : request.body.name,
                    "email" : request.body.email
                   }
            });
            response.status(200).json({
                success : true,
                data : "Updated Successfully"
            })
    }
    catch(error){
        response.status(404).send({
                message: "User not found",
                error,
        });
    }
)

我想到了。 我終於想出了如何在 heroku 中檢查我的服務器日志。在嘗試讀取請求正文時看到了錯誤。 做了更多的谷歌搜索。 最后發現我需要將 jsonParser 添加到 post 請求中,以便它能夠讀取 request.body。 現在可以了。 我絕對不會再忘記這個了……哈哈

app.post("/account/edit", jsonParser, auth, (request, response) => {
    User.updateOne({email: request.user.userEmail}, {
            "name":request.body.name,
            "email": request.body.email
        }
    )
        .then((result) => {
            response.status(200).send({
                message: "User updated successfully",
                result,
            })
        })
        .catch((error) => {
            response.status(404).send({
                message: "User not found",
                error,
            })
        });
    }
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM