Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

305
Views
Update and Create Array of Objects in MongoDB

I have a document in MongoDB structured like the below that I am trying to update and data value via the front-end input box.

{
    number: 1,
    question: "How often do you have a drink containing alcohol?",
    answer: [
      { score: 0, text: "Never (Skip to Questions 9-10)" },
      { score: 1, text: "Monthly or less" },
      { score: 2, text: "2 to 4 times a month" },
      { score: 3, text: "2 to 3 times a week" },
      { score: 4, text: "4 or more times a week" },
    ],
  },

My current code in the Express endpoint is not allowing me to update the data, and the error will raise up when I click the update button.

router.post("/questions/:id", async (req, res) => {
  try {
    const _id = req.params.id || req.query.id;
    const { number, question, answer } = req.body;
    await Question.findOneAndUpdate({ _id }, { number, question, answer });
  } catch (error) {
    res.render("error");
  }
});

While I am trying to print out the req.body to see what data I have sent over, apparently, it is probably the reason why I got errors:

{
  number: '1',
  question: 'How often do you have a drink containing alcohol?',
  answer: [ { text: [Array], score: [Array] } ]
} 

I am using EJS for its front end, the edit loop is like below, not sure if I have the name attribute correct in input tag.

<% for (let i = 0; i < question.answer.length; i++) {   %>
  <label for="answer">Answer <%= i + 1 %>:</label>
  <input type="text" id="answer" name="answer[][text]" value="<%= question.answer[i].text %>" required><br><br>
  <label for="score">Score <%= i + 1 %>:</label>
  <input type="number" id="score" name="answer[][score]" step="1" min="0" max="10" value="<%=question.answer[i].score %>" required><br><br>
<% } %>

Below is the screenshot of the data structure from MongoDB GUI:

enter image description here

I am facing the same issue with creating a new question with answers in the Array of Objects format, wondering if anyone can help with how I can update/create Array of Objects in MongoDB properly.

Appreciate your help!!!

Thank you very much.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!