Mongoose Follower和以下查询优化

时间:2016-03-28 04:47:47

标签: node.js mongodb mongoose

我在mongo中有一个文档,用于使用这个架构为我的社交应用程序维护关注者和关注者。我在本文档中有近3000条记录。

var FollowSchema = new Schema({
                uid : {
                    type: Schema.ObjectId,
                    ref: 'User'
                },
                fid : {
                    type: Schema.ObjectId,
                    ref: 'User'
                }
            });

目前,我正在抓取所有已登录用户的关注者用户,如下所示:

       Follow.find({ fid : req.user._id})
      .populate('fid' , {name,_id}).lean().exec(function(err,               details) {
                if (err) {
                    res.status(500).json(err);
                } else {
                    res.status(200).json(details);
                }
            });

不使用内部查询或Asycn,是否可以找到登录用户是否相互"跟随"追随者?

我查看了MapReduce和聚合,但不确定这是否有用。

赞赏任何示例代码。

1 个答案:

答案 0 :(得分:0)

不能在我的头脑中做这个猫鼬映射,但这是在mongodb中做到这一点的一种方法(4711这里是你的uid,注意它在查询中提到了3次)

db.follow.aggregate(
 {$match: {$or: [{uid:4711},{fid:4711}]}},    // Find all entries regarding user.
 {$project:                                   // Project user to uid,
  {z:                                         // followed/follower to fid and
   {$cond:[                                   // the type to followed/followed.
    {$eq:["$uid",4711]},
     {fid:"$fid", following:{$literal:1}},
     {fid:"$uid", followed:{$literal:1}}]
   }
  }
 },
 {$group:{_id:"$z.fid",                       // Group by fid to get the total
          following:{$sum:"$z.following"},    // type of the other user 
          followed:{$sum:"$z.followed"}}
 }
)

# You're followed by 3
# { "_id" : 3, "following" : 0, "followed" : 1 }
# You're following 4 and he/she is following you back
# { "_id" : 4, "following" : 1, "followed" : 1 }
# You're follwing 2
# { "_id" : 2, "following" : 1, "followed" : 0 }