以上示例均未显示在函数内部进行简单求和,如何从函数进行聚合查询?
基本上只是尝试将一组已知查询存储为Mongo上的函数
答案 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);