Automatic calculated fields

automation, mongodb, mongoose

Solution

I would make the `points` field a normal Number field, and increment (or decrement) it appropriately as you increment `upvotes` and `downvotes` (shown here using regular JS shell syntax, but the technique will work with mongoose as well):

// when upvoting
db.image.update({/* criteria */}, {$inc: {upvotes: 1, points: 1}})

// when downvoting
db.image.update({/* criteria */}, {$inc: {downvotes: 1, points: -1}})

If you have existing data, you'll need to generate the `points` field from the existing objects, but once you have it, it will be in sync due to the atomic nature of MongoDB updates and the `$inc` operator.

Problem

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] } }); ```

Original source