在mongo函数中执行汇总查询

时间:2019-09-23 20:29:22

标签: mongodb function aggregate

以上示例均未显示在函数内部进行简单求和,如何从函数进行聚合查询?

基本上只是尝试将一组已知查询存储为Mongo上的函数

1 个答案:

答案 0 :(得分:0)

您可以将查询定义为函数。假设博客中的帖子结构如下,您可以将其保存为收藏。如果您需要增加或减少favCount,可以按照以下步骤进行操作,

const PostSchema = new Schema(
  {
    //other necessary fields as title, description of the post..etc 
    favoriteCount: {
      type: Number,
      default: 0,
    },
  },
  { timestamps: true },
);


PostSchema.statics = {

  incFavoriteCount(postId) {
    return this.findByIdAndUpdate(postId, { $inc: { favoriteCount: 1 } });
  },

  decFavoriteCount(postId) {
    return this.findByIdAndUpdate(postId, { $inc: { favoriteCount: -1 } });
  }
};

export default mongoose.model('Post', PostSchema);
相关问题