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

Viewed 42

Okay so I am currently writing an API that when called, should update the current user in mongoDB using data passed in the request.

However, when I call findOneAndUpdate(), I get a 500 internal server error. (i will show a couple of the ways I've attempted to make it work below)

When I call findOne(), it finds and returns the correct user without issue. However then I ran into the issue of not being able to update the user, I tried user.name = request.body.name; followed by user.save(); but that did not work. So I decided to try findOneAndUpdate again.

here are a couple of ways I've tried so far

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,
            });
        })
    }
)

or originally I had

//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,
            });
        })
    }
)

Both of these return 500 errors. What am I doing wrong?

Here is where I call the 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;

Also if there are any ways I can improve my question, please let me know. I am still figuring out best practices, and trying to make each question clearer than the last.

2 Answers

Before trying below code can u check that email in User Schema is unique or not. If its unique and you're passing email that is already present in DB it will not modify the data.


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,
        });
    }
)

I figured it out! I finally figured out how to check my server logs in heroku. Saw the error was while trying to read the request body. Did more googling. Finally figured out that I needed to add jsonParser to the post request for it to be able to read the request.body. It works now! I'll certainly never forget this again... haha

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,
            })
        });
    }
)
Related