Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic calculated fields

Below is a Schema for my application. Under "meta" I have to fields that's called "upvotes" and "downvotes" and I want a field for the total amount of points (upvotes - downvotes). As for now I'm calculating this on the client side, but I also want to be able to sort by points (the image with most points first and descending).

Is there some way to auto calculate a field in Mongoose and if so, how is it done?

var ImageSchema = new Schema({
    name : String,
    size : Number,
    title   : String,
    body : String,
    buf : Buffer,
    date: { type: Date, default: Date.now },
    comments : [CommentSchema],
    meta : {
        upvotes : Number,
        downvotes : Number,
        points : ? // <- upvotes - downvotes
        favs : Number,
        uniqueIPs : [String],
        tags : [String]
    }
});
like image 974
holyredbeard Avatar asked Jan 16 '23 18:01

holyredbeard


1 Answers

You should use Mongoose middleware :

schema.pre('save', function (next) {
    // set points value based on positive and negatives 
})

This way, every time you save data, points value will be refreshed. The downside is that it will be refreshed even if down/upvotes aren't changed.

Warning : be extra carefull if several applications use the same DB, you want the same logic to be applied everywhere.

like image 112
Arnaud Rinquin Avatar answered Jan 25 '23 15:01

Arnaud Rinquin