A. *_*Lau 6 javascript mongoose mongodb
是否可以让 facet 作为对象而不是数组返回?需要访问result[0].total而不是仅仅访问似乎有点违反直觉result.total
代码(使用猫鼬):
Model
.aggregate()
.match({
"name": { "$regex": name },
"user_id": ObjectId(req.session.user.id),
"_id": { "$nin": except }
})
.facet({
"results": [
{ "$skip": start },
{ "$limit": finish },
{
"$project": {
"map_levels": 0,
"template": 0
}
}
],
"total": [
{ "$count": "total" },
]
})
.exec()
Run Code Online (Sandbox Code Playgroud)
您使用的每个字段都$facet代表单独的聚合管道,这就是您总是得到一个数组的原因。您可以使用$addFieldstotal用单个元素覆盖现有的。要获得第一项,您可以使用$arrayElemAt
Model
.aggregate()
.match({
"name": { "$regex": name },
"user_id": ObjectId(req.session.user.id),
"_id": { "$nin": except }
})
.facet({
"results": [
{ "$skip": start },
{ "$limit": finish },
{
"$project": {
"map_levels": 0,
"template": 0
}
}
],
"total": [
{ "$count": "total" },
]
})
.addFields({
"total": {
$arrayElemAt: [ "$total", 0 ]
}
})
.exec()
Run Code Online (Sandbox Code Playgroud)