Sunday, 7 May 2017

Mongoose field reset

I have a mongoose schema that looks like this:

var mongoose = require('mongoose');
var _ = require('lodash');
var Schema = mongoose.Schema;


var shopSchema = new mongoose.Schema({

    name: {type: String, trim: true},
    description: {type: String, trim: true},
    rating: Number,
    ratingsData: [{type: Number}]

});

shopSchema.methods.rate = function(rating){
    this.ratingsData.push(rating);
    this.rating = _.mean(this.ratingsData);
    return this.ratingsData;
}

module.exports = mongoose.model('Shop', shopSchema);

The rate method is supposed to append a value passed to it to the ratingsData field and then return the average of that array. The problem I'm having is that everytime the method is called, this.ratingsData is just an empty array. The previous values aren't saved for some reason. Therefore the average I get is always the rating passed to the method.

What am I doing wrong?



via Swailem95

No comments:

Post a Comment