我正在制作一个应用,其中我将设置一些测验集,其中将包含许多问题,选项和正确答案。
单个问题将以无答案的形式出现在用户面前,不久用户将选择选项并提交该表单,它将进入另一个名为“答案”的数据集。每个答案对象将带有“ participated_user_id”,“ quiz_id”,“ answers”。答案将包含每个“ question_id”和“ user_answer”。
现在,我需要一些查询,将这两个数据集合并在一起,并在“测验”集中为每个问题添加“ user_answer”。
{
_id : 856803,
title : My quiz title,
active : on,
questions : [
{
_id : 135224,
options : [a, b c, d],
question : here is my question one ?,
answer : a,
},
{
_id : 135229,
options : [a, b c, d],
question : here is my question two ?,
answer : a,
}
]
}
{
_id : 1234,
quiz_id : 856803,
answers : [
{
_id: 2367,
question_id : 135224,
answer : a
} ,
{
_id: 2364,
question_id : 135229,
answer : c
}
]
}
{
_id : 856803,
title : My quiz title,
active : on,
questions : [
{
_id : 135224,
options : [a, b c, d],
question : here is my question one ?,
answer : a,
user_answer : a
},
{
_id : 135229,
options : [a, b c, d],
question : here is my question two ?,
answer : a,
user_answer : c
}
]
}
答案 0 :(得分:0)
db.getCollection('quiz').findOne({}, function(err, doc){
db.getCollection('answers').findOne({quiz_id : doc._id}, function(err, ans){
doc.questions.forEach( function( item) {
for( let i = 0; i < ans.answers.length; i++ ) {
if( ans.answers[i].question_id === item._id )
item.user_answer = ans.answers[i].answer;
}
})
})
let _id = doc._id
delete doc._id // for handling duplicate key error in update
db.getCollection( 'quiz' ).update({_id: _id}, doc, function(err, result){
console.log( "doc updated as per your requirements")
})
})