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]
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With