我有一个名为Exam的收藏集。 我需要将数据填充到以下代码所示的同一集合中。 下面是我的路线的代码。
router.get('/fetchanswerbyid/:id',
auth,
async (req,res)=>{
try {
let user = await Exam.find({"_id":req.params.id}).populate('answers.user.answer.question_id', Exam) //Exam is the name of Exam model
res.json(user)
} catch (error) {
console.error(error.message)
}
})
下面是我的模型的代码。
const mongoose = require('mongoose')
const ExamSchema = new mongoose.Schema({
classroom:{
type:mongoose.Schema.Types.ObjectId,
ref:'classrooms'
},
exam_name:{
type: String,
required: true
},
subject:{
type: String,
required: true
},
questions:[
{
question:{
type: String,
required: true
},
answerA:{
type: String,
},
answerB:{
type: String,
},
answerC:{
type: String,
},
answerD:{
type: String,
},
checkedA:{
type: Boolean,
default: false
},
checkedB:{
type: Boolean,
default: false
},
checkedC:{
type: Boolean,
default: false
},
checkedD:{
type: Boolean,
default: false
},
pattern:{
type: String,
required: false
},
queType:{
type: String,
required: false
},
textAns:{
type: String
},
}],
answers:[{
user:[{
user_id:{
type:mongoose.Schema.Types.ObjectId,
ref:'user_collection'
},
answer:[{
question_id:{
type:mongoose.Schema.Types.ObjectId,
refPath: "exam"
},
checkedA:{
type: Boolean,
default: false
},
checkedB:{
type: Boolean,
default: false
},
checkedC:{
type: Boolean,
default: false
},
checkedD:{
type: Boolean,
default: false
},
textAns:{
type: String
},
}]
}]
}]
})
module.exports = mongoose.model('exam',ExamSchema)
当我请求带有考试ID的路线时,我希望从上面的“问题”数组中填充questions_id(在“答案”数组中)的数据。 目前,这就是我的输出在邮递员中的样子。
[
{
...
"subject": "AI / ML",
"exam_name": "a",
...
"questions": [
{
"checkedA": true,
"checkedB": false,
"checkedC": false,
"checkedD": false,
"_id": "5ee13e82169454eec35b7408",
"question": "abc",
"marks": "12",
.....
}
],
"__v": 0,
"answers": [
{
"user": [
{
"answer": [
{
"checkedA": false,
"checkedB": false,
"checkedC": false,
"checkedD": false,
"_id": "5ee5419d0d63bfc75e81b45b",
"question_id": null
}
],
"_id": "5ee5419d0d63bfc75e81b45a",
"user_id": "5ed22a3a6e8451061f4e1855"
}
],
"_id": "5ee5419d0d63bfcs214d2259"
}
]
}
]
对于“ question_id”,其显示为“ null”,应在同一集合中填充问题数组。
有人可以帮我吗?