【问题标题】:Followers - mongodb query check追随者 - mongodb 查询检查
【发布时间】:2018-11-27 20:51:19
【问题描述】:

我的数据库中有 2 个集合。一个叫用户

{
   _id: storeUserId,
   name: ...,
   etc
}

另一个叫Following

{
   userId: ...,
   followingUserId: ...
}

userId是当前用户id,followingUserId是当前用户想要关注的id。

例如,在用户集合中我有:

{
  _id: userIdOne,
   etc
},
{
  _id: userIdTwo,
  etc
}

在以下收藏中我有:

{
  userId: userIdThousand,
  followingUserId: userIdTwo
}

当我运行查找查询时

db.bios.find();

我明白了

   {
    "_id": userIdTwo,
    "username": "random27005688"
},
{
    "_id": userIdThree
    "username": "random232111"
},
{
    "_id": userIdOne
    "username": "random2702"
}
]

结果是我想要的,但我想为每个结果项添加一个“isFollowed”字段以检查以下状态。我有一个用户 ID,可以说:'userIdThousand',我想用它来检查基于我的以下集合的每个结果项。例如,

check if userIdThousand is following userIdOne
check if userIdThousand is following userIdTwo, etc.

以下是我的预期结果。谢谢!

[
{
    _id: userIdTwo,
    "username": "random27005688",
    "isFollowed": true
},
{
    "_id": userIdThree
    "username": "random232111",
    "isFollowed": false
},
   {
    "_id": userIdOne
    "username": "random2702",
     "isFollowed": false
},
]

【问题讨论】:

  • 你能从查询中发布你想要的输出吗
  • 我想我的问题已经有了。基本上我只需要一个“isFolwed”字段来检查关注状态

标签: node.js mongodb mongoose mongodb-query


【解决方案1】:

也许你可以把它分成两步。

1。查询用户并获取结果

例如,你得到一个用户。

{
    _id: userIdTwo,
    "username": "random27005688",
}

2。查询关注,获取用户是否被关注。

比如

has_followed=db.Following.find({"userId":userIdTwo}).count()

不是最好的解决方案,但它可能会帮助你。

【讨论】:

    【解决方案2】:

    您需要$lookup 才能从与followingUserId 匹配的第二个集合中获取数据,然后您可以使用$filter 仅获取具有特定_id 的关注者并检查新数组是否有任何元素(使用$size)这意味着该用户被其他用户关注:

    db.User.aggregate([
        {
            $match: {
                _id: { $ne: "userIdOne" }
            }
        },
        {
            $lookup: {
                from: "Following",
                localField: "_id",
                foreignField: "followingUserId",
                as: "followers"
            }
        },
        {
            $addFields: {
                followers: {
                    $filter: { input: "$followers", as: "follower", cond: { $eq: [ "$$follower._id", "userIdOne" ] } }
                }
            }
        },
        {
            $project: {
                _id: 1,
                username: 1,
                isFollowed: { $gt: [ { $size: "$followers" }, 0 ] }
            }
        }
    ])
    

    【讨论】:

    • 哦,太好了!你能解释一下这条线的作用吗: isFollowed: { $gt: [ { $size: "$followers" }, 0 ] }
    • $size 返回数组的长度,因此如果该长度大于零($gt),则表示用户被某人关注
    • 在 $lookup 中,有没有一种方法可以输入 ''userIdOne",这样它会在 $match 的返回结果中针对所有用户检查 userIdOne。原因是 isFollowed 总是返回 false,因为$lookup 中的 isFollowed 为空。谢谢!
    • @KevinVuD 我不确定我是否理解正确,但我想你可以通过修改$match 来实现
    • 我想要的只是获取 User 集合中的所有用户信息,然后使用我必须检查每个查询结果的 userId 来查看该 userId 是否遵循返回查询中的任何用户信息。
    猜你喜欢
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 2021-10-09
    • 2017-12-17
    相关资源
    最近更新 更多