【发布时间】:2022-11-23 02:47:26
【问题描述】:
我正在做一个社交媒体,我有 2 个模式的问题。用户和追随者。当一个用户关注另一个用户时,一个新文档被添加到 followers 方法中,其中包含 who dollows who 信息。创建文档后,post hook 使用带有聚合管道的静态函数运行,该函数计算关注用户的关注者和关注用户的关注者以及修改它之后,直到它正确但是当我尝试做同样的事情时用户取消关注其他人,此帖子挂钩无法正常工作。
带有聚合管道的跟随者 schema.statics 函数:
followersschema.statics.AdjustFollowersFollowing = async function(FOLLOWEDID,FOLLOWINGID){
try{const statsfollowedid = await this.aggregate([{ //THIS AGREGATION PIPELINE GETS THE EXACT NUMBER OF FOLLOWERS THAT THE FOLLOWED USER HAS
$match: { followedid : FOLLOWEDID}
},{
$group: {
_id: FOLLOWEDID,
numFollowed: {$sum:1}
}
}]);
const statsfollowingid = await this.aggregate([{//THIS AGREGGATION PIPELINE GETS THE EXACT NUMBER OF PERSON THAT FOLLOWS THE FOLLOWING USER
$match: { followingid : FOLLOWINGID}
},{
$group: {
_id: FOLLOWINGID,
numFollowing: {$sum:1}
}
}]);
await User.findByIdAndUpdate({_id : FOLLOWEDID},{numfollowers:statsfollowedid[0].numFollowed})
await User.findByIdAndUpdate({ _id : FOLLOWINGID},{numfollowing:statsfollowingid[0].numFollowing})
}catch(err){
console.log(err);
}
}
我正在尝试为 .findOneAndRemove 方法 mongoose 的后挂钩创建聚合管道。首先,我尝试在 post hook 上执行此操作。(相同的代码适用于 hook .pre('save)
this._conditions 得到删除前的信息
followersschema.post('findOneAndRemove',function(){
console.log(this._conditions.followedid); console.log(this._conditions.followingid) //execute function for AdjustFollowersFollowing of both users after unfollow
this.constructor.AdjustFollowersFollowing(this._conditions.followedid,this._conditions.followingid)
});
我收到的错误信息是:
TypeError: this.constructor.AdjustFollowersFollowing 不是函数
up 也是我试过的
我接下来要做的是
【问题讨论】:
标签: node.js mongodb express mongoose