Home > Software design >  Editing MongoDB object with Express
Editing MongoDB object with Express

Time:10-10

I'm trying to allow users to edit their profiles to display a message of their choosing.

This code catches an error when the form is submitted and I'm unsure why. I'm using express and mongoose. Any help is greatly appreciated!

The .jsx file that makes up the frontend:

import { Cancel, Room } from "@material-ui/icons";
import axios from "axios";
import { useRef, useState } from "react";
import "./settings.css";

export default function Settings({ setShowSettings }) {

  const [success, setSuccess] = useState(false);
  const [error, setError] = useState(false);
  const inputRef = useRef();
  const myStorage = window.localStorage;
  var name = useState(myStorage.getItem("user"));
  const handleSubmit = async (e) => {
    e.preventDefault();
    const update = {profile: inputRef.current.value}
    try {
      await axios.post("/update/:username", update);
      setError(false);
      setSuccess(true);
    } catch (err) {
      setError(true);
    }
  };

  return (
    <div className="settingsContainer">
      <h1>{name}'s Settings</h1>
      <Cancel
        className="settingsCancel"
        onClick={() => setShowSettings(false)}
      />
      <form onSubmit={handleSubmit}>
<textarea ref={inputRef} type="textarea" id ="profiletext" placeholder="create a profile"/>
        <button className="settingsBtn" type="submit">
          Save
        </button>
        {success && (
          <span className="success">Profile updated!</span>
        )}
        {error && <span className="failure">Something went wrong!</span>}
      </form>

      </div>

  );
}

The route I'm using:

  router.post('/update/:username', async (req, res) => {
  const update = {profile: req.body.profile}
  const filter = {username: "testtt"}
  const updatedDocument = await User.findOneAndUpdate(filter, update, { new: true });

  return res.status(200).send(updatedDocument);
});

CodePudding user response:

You should use the name param while making the axios request. Express does the route matching and parameter population for you in req.params

Client: (wtih express server running on 3000 locally at /user. Can modify it based on how routes are exposed in the code)

await axios.post(`http://localhost:3000/user/update/${name}`, update);

Server:

const filter = {username: req.params.name}
const updatedDocument = await User.findOneAndUpdate(filter, update, { new: true });

CodePudding user response:

First define state in a better way.

  • if you don't destructure the state you can't use "name" variable directly in the component.

  • initialize the state with a function so the expression inside parantheses won't run in every render.

    const  [name, setName] = useState(() => myStorage.getItem("user"));
    

-then send request with axios like this

await axios.post(`http://localhost:3000/user/update/${name}`, update);

-then you can update the profile in the express handler like this. (I am assuming you have "username" field in the User model.

const update = {profile: req.body.profile}
  const filter = {username: req.params.username}
  const updatedDocument = await User.findOneAndUpdate(filter, update, { new: true });
  • Related