0

I am trying to update this array object: enter image description here

I am trying to make it in this way

static async InsertAnwer(product, answer, questionId) {

    let newAnwers = []

    try {

        product.secao.forEach(element => {
            if(element._id == questionId && element.answers.length > 0) {
                newAnwers.push(...element.answers)
                newAnwers.push(answer)
                element.answers = newAnwers
            }else if(element._id == questionId) {
                newAnwers.push(answer)
                element.answers = newAnswers
            }
        })

        await product.save()
        return product
    }catch(err) {
        console.log(err)
        return new EndMsg(500, err)
    }
}

The code is going into the secound "IF", but anyways the answers array in Mongo Object is not updating

  • can you be more detailed in what are you using... `product.save()` is not MongoDB, it's `updateOne` or `updateMany`, are you using Mongoose? I miss that as a tag to be sure. if Mongoose, then `save` would create a new document, you would be better using `update`, here's [an answer in case you are using mongoose](https://stackoverflow.com/a/15691950/28004) – balexandre Jul 08 '23 at 20:10
  • Yes. I am using mongoose, and i am going to take a look in this answer. Thank you – Emmanuel Medeiros Jul 10 '23 at 13:01

2 Answers2

0

If you are using mongoose, you can do a direct query for that using the $push operator:

const updatedProduct = await ProductModel.findOneAndUpdate(
  { _id: productId },
  { $push: { `secao.${secaoIndex}.answers`: newAnswer } },
  { new: true }
)
Nathan Barel
  • 348
  • 2
  • 14
0

Answer

   static async InsertAnswer(product, answer, questionId) {
      try {
          // Get the question based on question id
          const question = product.secao.find(q => q._id.toString() === questionId);

          if (question) {
            // Push the new answer into the answers array
            question.answers.push(answer);

            // Save the updated product document
            await productDoc.save();

            console.log('Answer added successfully');
          } else {
            console.log('Question not found');
          }
      } catch (error) {
        console.error('Error:', error);
      }
    }
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 10 '23 at 00:36
  • I think your answer could work, but i have index in my "product.secao" object. So, due to this, i am not finding any question. To be clear: I only get the question._id when i find the "secao" index, so the correct query would be something like "product.secao[0].find...", am i right? – Emmanuel Medeiros Jul 10 '23 at 13:44
  • But secao array might be have more than one object. We can't relay on 0th index secao object. – G Madhabananda Patra Jul 10 '23 at 19:43