代碼沒有在答案陣列中添加答案......請解釋如何撰寫正確的方法來實作它?'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); 括號中的答案將從 req.body 獲得,但這也不起作用。
uj5u.com熱心網友回復:
你的答案是一個陣列。您不能將值設定為物件。如果要將物件添加到陣列。讓我們使用推送功能。
例如:question.answers.push({ answer: req.body.answer,postedBy: “userId” }); 問題.save()
uj5u.com熱心網友回復:
Answers 欄位是一個陣列,您應該在 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);
})
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/333158.html
