代码没有在答案数组......中添加答案请解释如何写正确的方法来实现它?'id'是问题的名称,用于参数。
模式:
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请求:
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);
})
})
我还尝试了question.answers.answer.push(answer);其中括号内的答案将从请求中获得。正文,但这也不起作用。
Answers字段是一个数组,您应该指定哪个答案内部答案数组
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 }
另一个解决方案:
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);
})
})
你的答案是一个数组。不能将值设置为对象。如果你想添加一个对象到数组。让我们使用推送功能
交货:question.answers。Push ({answer: request .body。answer, postedBy: " userId "});question.save ()