Mongoose & getting average of ratings in a collection?
<p>I have a NodeJS based application using Mongoose. I am wanting to create a response where there values are an average of ratings provided by people who have responded to a questionnaire, for each question asked. </p>

<p>My Schema looks as follows:</p>

<pre><code>const questionnaireResultSchema = new Schema({      
   user: { type: ObjectId, ref: 'User' },
   questionnaire: { type: ObjectId, ref: 'Questionnaire' },
   rating: [{
       id: Number,
       question: String,
       value: Number
   }]
},{
    timestamps: true
}).index({user: 1, questionnaire: 1}, {unique: true});
</code></pre>

<p>I have looked at the Mongoose <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/avg/" rel="nofollow">aggregator operator</a>, but I am not sure how I would apply it to my case. Pseudo code would look as follows:</p>

<ul>
<li>Find all questionnaire results for questionnaire of id xyz</li>
<li>Provide a result where the ratings for each questionnaire result has be averaged</li>
</ul>

<p>For example the response would look as follows:</p>

<pre><code>[{
   id: 1,
   question: 'How strongly do you feel about candidate A?',
   value: 12 // averaged value
 },{
   id: 2,
   question: 'How strongly do you think we should change the sky color to green?',
   value: 31 // averaged value
 },{
   id: 3,
   question: 'How strongly do you think your answers count?',
   value: 20 // averaged value
 }]
</code></pre>

<p>I have tried:</p>

<pre><code>QuestionnaireResultSchema.aggregate([{ 
    $match: {
        questionnaire: questionnaire
    }},
        {$project: {
            scores: { $avg: '$scores'}
        }}
    ]);
</code></pre>

<p>This just provides the JSON:</p>

<pre><code>[{
    "_id": "57bbd4b495407f6145b3ba9f",
    "scores": null
}]
</code></pre>

<p>A sample document in a collection would like:</p>

<pre><code> {
    user: ObjectId("57bca30536e376c653f439bb")
    questionnaire: ObjectId("37bca0feedb0bc470353ab")
    scores:     [{
        id: 1,
        question: 'How strongly do you feel about candidate A?',
        value: 3
      },{
        id: 2,
        question: 'How strongly do you think we should change the sky color to green?',
        value: 4 // averaged value
      },{
        id: 3,
        question: 'How strongly do you think your answers count?',
        value: 5 // averaged value
      }]
   }
</code></pre>

<p>While I could calculate the averages myself, if Mongoose provides the functionality, I would rather leverage that.</p>

<p>Any help would be appreciated.</p>