Debug School

rakesh kumar
rakesh kumar

Posted on

How to store data in array while updating collection in node js

const updatedClient = await QuestionModel.findByIdAndUpdate(_id, values, {
  new: true,
})
Enter fullscreen mode Exit fullscreen mode

Model

 checkone: {
        type: [String],        
      },
textanswer: {
          type: [String],         
        },
        email: {
          type: [String],         
        },
Enter fullscreen mode Exit fullscreen mode

Controller
Apply if else condition
if question exist then update otherwise create

const { Question,  answerone, answertwo, answerthree, answerfour,checkone,checktwo,checkthree,checkfour,textanswer,email,userId,questionid} =
  req.body

Enter fullscreen mode Exit fullscreen mode
const myanswer=checkone?'answerone' + "-" + checkone:checktwo?'answertwo' + "-" + checktwo:checkthree?'answerthree' + "-" + checkthree:'answerfour' + "-" + checkfour;
Enter fullscreen mode Exit fullscreen mode
 const existingq = await FeedbackModel.findOne({ questionid });
          console.log(existingq);

            if(existingq)
            {
            existingq.checkone=[... existingq.checkone,myanswer]
            existingq.email=[... existingq.email,email]
            existingq.textanswer=[... existingq.textanswer,textanswer]
            feedback= await FeedbackModel.findByIdAndUpdate(existingq._id,existingq,{new:true})
          console.log(feedback)
                  res.status(200).json({ feedback }) 
                }
                else
                {
          const values = {
            question: Question,
            answer_one:answerone,
            answer_two:answertwo,
            answer_three: answerthree,
            answer_four:answerfour,
            checkone:myanswer,           
            textanswer:textanswer,
            email:email,
            userId:userId,
            questionid:questionid,
            sentiment:text,
            score:score,
            is_active: true,
          }
          console.log('value ke user isds')
          console.log(values)  
          const feedback = await FeedbackModel.create(values)
          console.log(feedback)
          res.status(200).json({ feedback }) 
        }     
Enter fullscreen mode Exit fullscreen mode

in database

Image description

Top comments (0)