mongodb聚合$size不返回结果?

jjjwad0x  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(349)

我有这样的数据:

[
  {
    "_id": "60ccb13a21d65f0c7c4c0690",
    "username": "testuser",
    "friendRequests": [
      {
        "_id": "60ccb13a21d65f0c7c4c0690",

      }
    ]
  }
]

代码如下:

router.use(async function(req, res, next){

    try {
        res.locals.fr = await User.aggregate([
            {$match:{username: "testuser"}},    
            {$project: {
                frCount: {
                  $size: "$friendRequests"
                }
              }}]),
        res.locals.login = req.isAuthenticated();
        res.locals.newProfile = req.user;
        next();
    }
    catch {
        res.locals.login = req.isAuthenticated();
        res.locals.newProfile = req.user;
        next();
    }

});

它不应该还这个吗?

[
  {
    "frCount": 1,
    "_id": ObjectId("60ccb13a21d65f0c7c4c0690")
  }
]

那么如果我把它放在ejs中:

<p>requests: <%= fr.frCount %></p>

它不应该返回1吗?然而,它什么也不返回,我不知道为什么。

fnatzsnv

fnatzsnv1#

返回的不是对象。它是一个数组:https://mongoplayground.net/p/dcvrgl2exxp

[
  {
    "_id": "60ccb13a21d65f0c7c4c0690",
    "frCount": 2
  }
]

所以,你需要这样做 fr[0].frCount 以获取值。

相关问题