使用mongo $ lookup和$ project

时间:2017-07-26 14:35:39

标签: mongodb mongoose aggregation-framework

我正在构建一个将人们配对的应用程序。您可以查看人员列表,一次连接或关闭配置文件。

用户模型

//user
{
    _id: ObjectId,
    name: String
    ...
}

作为用户,当我想要获取要联系的新人时,我将对user表执行查询。

当用户批准或拒绝与用户建立联系时,我会在usermatches集合中为每个决定创建一个条目。

usermatch model

//usermatches table
{
  _id: ObjectId,
  requester: ObjectId,
  receiver: ObjectId,
  approved: boolean
}

现在将来查询人们要连接,我将再次查询user表。

但是,我不想让任何用户与我在usermatches表中共享一行。

因此,当我请求用户列表时,通过使用查找,我将收集他们请求和收到的匹配。

User.aggregate([
    {
        $lookup: {
            from: "usermatches",
            localField: "_id",
            foreignField: "requester",
            as: "requested_matches"
        }
    },
    {
        $lookup: {
            from: "usermatches",
            localField: "_id",
            foreignField: "receiver",
            as: "received_matches"
        }
    }
], (err, result) => {
    console.log(err);
    console.log(result);
});

我需要做的是从查询中消除用户,与我共享usermatches行。因此,我需要针对请求者检查我的_id,或者为每个用户及其每个集合检查usermatch条目中的接收者_id值。

var my_id = "abc123";    
User.aggregate([
    {
        $lookup: {
            from: "usermatches",
            localField: "_id",
            foreignField: "requester",
            as: "requested_matches"
        }
    },
    {
        $lookup: {
            from: "usermatches",
            localField: "_id",
            foreignField: "receiver",
            as: "received_matches"
        }
    },
    {
        $project: {
            _id: 1,
            ...
            //more user data
            requested_matches: {
                // I need to filter out users who contain my ```_id``` in their ```requested_matches``` or ```received_requests```.
            },
            received_matches: {
                // same here
            }    
        }
    }
], (err, result) => {
        console.log(err);
        console.log(result);
});

如何在其requested_matches或received_requests中过滤掉包含user的{​​{1}}行。即my_idrequested_matches.reciever == my_id

更新 - 已解决

我根本不需要使用received_requests.requestor == my_id。我所要做的只是填充这些集合,然后检查我的request.user._id

离开加入mongo,真是时候活着。

$project

0 个答案:

没有答案