当输入为1时,mongoose map reduce返回错误的结果

时间:2018-06-10 19:01:11

标签: node.js mongoose mapreduce

我想尝试mongoose map reduce函数,结果如下:

// See: http://mongoosejs.com/docs/api.html#mongoose_Mongoose-Model
function mapReduceStatistic(homework) {
    let mapReduceObject = {};
    mapReduceObject.map = function () {
        // each submission contains the exercises array which stores the picked answer for each exercise of the student
        this.exercises.forEach(function (pickedAnswer, i) {
            // key is index of the exercise in exercise array
            // value is map of:
            emit(i, pickedAnswer);
        });
    };
    mapReduceObject.reduce = function (keyExerciseIndex, mapArray) {
        let pickedAnswers = [];
        pickedAnswers[0] = 0;
        pickedAnswers[1] = 0;
        pickedAnswers[2] = 0;
        pickedAnswers[3] = 0;
        mapArray.forEach(function (pickedAnswer, i) {
            pickedAnswers[pickedAnswer]++;
        });
        return {pickedAnswers: pickedAnswers};
    };
    mapReduceObject.query = {
        homework: homework._id
    };
     return SubmissionModel.mapReduce(mapReduceObject).then((statistics) => {
         if(!statistics) throw Error("Error in map reduce");
         return statistics;
    });
}

它工作正常,并映射当前作业的每个提交的每个练习。对于每个学生,有一个提交的作业,我想减少每个练习的选择答案(每个练习有4种可能的选项,您可以从中选择答案)。

提交模式:

//submission Schema with an array of indexes of the picked answer of each 
//exercise of an homework and the assigned Homework
// exercises values between zero and three
const SubmissionSchema = new mongoose.Schema({
    exercises:  {
        type: [Number],
        required: true
    },
    homework: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Homework',
        required: true
    },
    student: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    }
},{ collection: 'submission' });

问题:如果只有一个输入模型,则无效。如果只有一个学生提交了他的作业,因此在数据库中只有一个提交了这个作业,则map reduce会将submission.exercises数组的每个值作为数组结果的一个值而不是mapAnwers返回。

当数据库中只有一个模型时,这是错误的结果:

    { results: 
   [ { _id: 0, value: 0 },
     { _id: 1, value: 0 },
     { _id: 2, value: 1 } ],
  stats: 
   { processtime: 51,
     counts: { input: 1, emit: 3, reduce: 0, output: 3 },
     timing: 
      { mapTime: 0,
        emitLoop: 51,
        reduceTime: 0,
        mode: 'mixed',
        total: 51 } } }

为什么会这样?看起来map和reduce甚至不会运行一次,而是返回结果数组。我甚至可以在reduce函数中返回{“Hello World”},它仍会打印练习数组而不是Hello World。

感谢您的支持!

有关完整代码,请参阅:https://github.com/andrelandgraf/high5-learning-backend 如果您有更多代码段或信息,请告诉我们。

0 个答案:

没有答案