从同一个表中获取数据时,我遇到了一个问题。我有一个名为“user_followings”的集合,其中包含 userId 和 targetUserId。userId 跟在 targetUserId 之后。以下是获得我的追随者的集合结构---
- _ID
- 用户身份
- 目标用户 ID
现在我需要根据userId获取记录作为获取数据,还需要检查每个返回的用户是否关注我以下状态(我的关注状态)将从同一个集合返回。
这是我写的代码----
UserFollowingModel.find({ targetUserId: req.user._id }).populate("user", "_id name email")
.limit(15)
.skip(15 * page)
.lean()
.then(userFollowers => {
var promise = new Promise((resolve, reject) => {
userFollowers.forEach(function (userFollower, key, array) {
UserFollowingModel.find({ userId: req.user._id, targetUserId: userFollower.userId }).countDocuments().then(myUserFollowing => {
console.log(myUserFollowing);
userFollowers[key].myFollowingStatus = myUserFollowing > 0 ? 'YES' : 'NO';
if ((array.length - 1) == key) {
resolve();
}
});
});
});
promise.then(() => {
return apiResponse.successResponseWithData(res, 'Successful', { total_records: count, data: userFollowers });
});
});
此代码在我的本地运行良好,但在生产中它挂起并返回代理错误 503。我尝试使用聚合但无法获得所需的响应,即使聚合显示来自收集的所有数据。
请建议我们如何解决它。
提前致谢