給定一個使用時間戳的基本 Mongoose 用戶架構(因此 createdAt 和 updatedAt 默認可用),我正在嘗試構建一個包含使用聚合的分頁服務器端的查詢。
到目前為止,當資料庫中有資料并且任何過濾器與集合中的任何專案匹配時,我已經實作了以下效果。
{
"users": [
{
"_id": "61c331f4bd87407c01b81324",
"bio": "??",
"surname": "Doe",
"name": "John",
"verified": true,
"disabled": false,
"username": "user1235",
"score": 1
}
],
"pagination": {
"total": 1,
"limit": 10,
"page": 1,
"pages": 1
}
}
但是,如果沒有專案符合條件,這只會回傳一個空陣列,從而丟失分頁部分。我的猜測是 facet 部分不是我期望的那樣在這里作業。
const findUsersQuery = await this.userModel.aggregate()
.match(query)
.sort({ cratedAt: -1 })
.project({
password: 0, email: 0, roles: 0, __v: 0,
facebookId: 0, googleId: 0, createdAt: 0,
updatedAt: 0, birthday: 0
})
.facet({
total: [{
$count: 'createdAt'
}],
data: [{
$addFields: {
_id: '$_id'
}
}]
})
.unwind('$total')
.project({
users: {
$slice: ['$data', ((page * limit) - limit), {
$ifNull: [limit, '$total.createdAt']
}]
},
pagination: {
total: '$total.createdAt',
limit: {
$literal: limit
},
page: {
$literal: page
},
pages: {
$ceil: {
$divide: ['$total.createdAt', limit]
}
},
}
})
return findUsersQuery[0]
我曾嘗試在某些地方使用 $ifNull,甚至在 facet 階段,為了只回傳 0 或空陣列以回傳相同的結構(保留用戶陣列和分頁塊),但無濟于事:
.project({
users: {
$ifNull: [
{
$slice: ['$data', ((page * limit) - limit), {
$ifNull: [limit, '$total.createdAt']
}]
},
[]
]
},
pagination: {
total: {
$ifNull: ['$total.createdAt', 0]
},
limit: {
$literal: limit
},
page: {
$literal: page
},
pages: {
$ifNull: [
{
$ceil: {
$divide: ['$total.createdAt', limit]
}
},
0
]
},
}
})
當沒有專案符合條件時,如何使用 $ifNull(如果這是最好的方法)以保持相同的回應結構?像這樣:
{
"users": [],
"pagination": {
"total": 0,
"limit": 10,
"page": 1,
"pages": 1
}
}
任何幫助將不勝感激。
uj5u.com熱心網友回復:
您不需要使用$ifNull此處,您的問題源于$unwind行為。
你想preserveNullAndEmptyArrays在$unwind
3.2 新版功能:要輸出缺少陣列欄位、null 或空陣列的檔案,請使用 preserveNullAndEmptyArrays 選項。
即使“空”,這也會保留檔案,如下所示:
.unwind({
path: "$total",
preserveNullAndEmptyArrays: true
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/393895.html
上一篇:MYSQL基礎學習筆記
