Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

307
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda