Mongodb聚合$size没有返回结果



我有这样的数据:

[
{
"_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吗?然而,它什么也不回,我不知道为什么。

返回的不是Object。它是一个数组:https://mongoplayground.net/p/dCVRGl2EXxP

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

因此,您需要执行fr[0].frCount来获得值。

最新更新