Home > front end >  How to post request for a particular field of array in mern stack
How to post request for a particular field of array in mern stack

Time:10-23

The code does not add answer in answers array......pls explain how to write the correct way to implement it? The 'id' is of the question, used for params.

Schema:

const QuestionSchema = new mongoose.Schema({
    qtitle:{
        type:String,
        required:true
    },
    descofq:{
        type:String,
        required:true
    },
    pic:{
        type:String,
        default:"no photo"
    },
    answers:[
        {
            answer:{
                type:String,
                required:false
            },
            picofa:{
                type:String,
                default:"no photo"
            },
            postedBy:{
                type:mongoose.Schema.Types.ObjectId,
                ref:"USER"
            }
        }
    ]
    }
})

POST request :

router.post('/answer/:id',authenticate,(req,res)=>{
    Question.findById(req.params.id).then(question=>{
        question.answers.answer = req.body.answer;
        question.save().then(result=>{
            res.json(result)
        }).catch(err=>{
            res.status(400).send(err);
        })
    }).catch(err=>{
        res.status(200).send(err);
    })
})

I also tried question.answers.answer.push(answer); where the answer in brackets will be acquired from req.body, but this also didn't work.

CodePudding user response:

Your answers is an array. You cannot set a value as an object. If you want to add an object to array. Let use push function.

Ex: question.answers.push({ answer: req.body.answer, postedBy: “userId” }); question.save()

CodePudding user response:

Answers field is an array you should specify which answer inside answers array

router.post('/answer/:id',authenticate,(req,res)=>{
    Question.findById(req.params.id).then(question=>{
        question.answers.push(req.body.answers);
        question.save().then(result=>{
            res.json(result)
        }).catch(err=>{
            res.status(400).send(err);
        })
    }).catch(err=>{
        res.status(200).send(err);
    })
})

Example: req.body.answers = { answer: "bla bla..", picofa: "bla bla", postedBy: userId }

Another solution:

router.post('/answer/:id',authenticate,(req,res)=>{
    Question.findById(req.params.id).then(question=>{
        question.answers[0].answer = req.body.answer;
        question.save().then(result=>{
            res.json(result)
        }).catch(err=>{
            res.status(400).send(err);
        })
    }).catch(err=>{
        res.status(200).send(err);
    })
})
  • Related