hol*_*ard 4 automation mongoose mongodb
下面是我的应用程序的架构。在“元”下,我必须有一个名为“赞成票”和“反对票”的字段,并且我想要一个表示总点数的字段(赞成票 - 反对票)。至于现在,我正在客户端计算这个,但我也希望能够按点排序(首先是最多点的图像,然后降序排列)。
有没有某种方法可以自动计算 Mongoose 中的字段,如果有,是如何完成的?
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]
}
});
Run Code Online (Sandbox Code Playgroud)
您应该使用Mongoose 中间件:
schema.pre('save', function (next) {
// set points value based on positive and negatives
})
Run Code Online (Sandbox Code Playgroud)
这样,每次保存数据时,积分值都会刷新。缺点是即使反对票/赞成票没有改变,它也会被刷新。
警告:如果多个应用程序使用相同的数据库,请格外小心,您希望在所有地方应用相同的逻辑。
| 归档时间: |
|
| 查看次数: |
5465 次 |
| 最近记录: |