0

I have a User model and trying to add education field to mongoDB as json object as follows,

User model

education: {
    "school": String,
    "years":Number
  },

Client

//add Education section
  const updateEducation = async (e) => {
    e.preventDefault();
    await fetch(`http://localhost:5000/api/user/updateEducation`, {
      method: "PUT",
      headers: { "Content-Type": "application/JSON", token: accessToken },
      body: JSON.stringify({ userid: userid, educationSchool: educationSchool,
        educationYearText: EducationYear}),
    })
      .then((res) => res.json())
      .then((data) => {
        console.log("User education is:", data.education +""+data.educationYear);
      });
  };

Server

const updateEducation = async (req, res) => {
  try {
    const user = await User.findOneAndUpdate(
      { _id: req.body.userid },
      {
        $set: {
          'education.school': req.body.educationSchool,
          'education.years': req.body.educationYearText,
        },
      }
    );

    if (!user) {
      res.status(404).json("user not exist");
    }

    res
      .status(200)
      .json({
        education: user.education.School,
        educationYear: user.education.years,
      });
  } catch (error) {
    res.status(500).send({ error: error.message });
  }
};

When im hitting this endpoint in postman http://localhost:5000/api/user/updateEducation

{
"userid":"63bbe4df75dca5aac7576e47",
"educationSchool":"Test college",
"educationYearText":"2018"
}

Im getting { "error": "Plan executor error during findAndModify :: caused by :: Cannot create field 'school' in element {education: []}" }

Whats wrong?

1 Answer 1

1

You should $push into an array:

const user = await User.findOneAndUpdate(
    { _id: req.body.userid },
    {
      $push: {
        education: {
            school: req.body.educationSchool,
            years: req.body.educationYearText,
        }
      },
    },
    { new: true }
  );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.