skip to Main Content

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

2

Answers


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

    const updatedProduct = await ProductModel.findOneAndUpdate(
      { _id: productId },
      { $push: { `secao.${secaoIndex}.answers`: newAnswer } },
      { new: true }
    )
    
    Login or Signup to reply.
  2. 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);
          }
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search