Auto Computed Fields

Below is a diagram for my application. In the meta section, I have fields called upvotes and downvotes, and I want a field for the total number of points (upvotes - downvotes). At the moment I am counting this on the client side, but I also want to be able to sort by points (the image with the most points at the beginning and the descent).

Is there a way to automatically 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] } }); 
+4
source share
2 answers

I would make the points field a normal Number field and increase (or decrease) it accordingly while you increase upvotes and downvotes (shown here using the usual JS shell syntax, but this method 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 need to generate a points field from existing objects, but as soon as you get it, it will be synchronized due to the atomic nature of MongoDB updates and the $inc operator.

+4
source

You should use Mongoose middleware :

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

Thus, every time you save the data, the value of the points will be updated. The downside is that it will be updated even if down / upvotes are not changed.

Warning: be careful if the same database is used in several applications, you want the same logic in all cases.

+4
source

Source: https://habr.com/ru/post/1411156/


All Articles