feat: add sorting order

This commit is contained in:
Chen, Tai-Lin committed 2023-12-13 15:05:25 +08:00
1 parent 1b94ae75ca
commit c6733814ba
3 files changed
+39 -7

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
/* eslint-disable class-methods-use-this */
// eslint-disable-next-line max-classes-per-file
class Order {}
export class Asc extends Order {
matchStage(nextKey) {
return { $gt: nextKey }
}
order() {
return 1
}
}
export class Desc extends Order {
matchStage(nextKey) {
return { $lt: nextKey }
}
order() {
return -1
}
}
+6 -1
View File
@@ -1,3 +1,4 @@
import { Desc } from '../constants.js'
import { userList, userCount } from '../models/users.js'
export async function userListController(req, res) {
@@ -8,7 +9,11 @@ export async function userListController(req, res) {
// const totalUsers = await userCount()
// const maxPages = Math.ceil(totalUsers / itemsPerPage)
const users = await userList({ nextKey, itemsPerPage })
const users = await userList({
nextKey,
itemsPerPage,
order: new Desc(),
})
const newNextKey = users[users.length - 1]?._id
res.render('users', {
+10 -6
View File
@@ -1,5 +1,5 @@
import { Session, User } from '@linux-odyssey/models'
import mongoose from 'mongoose'
import { Session, User } from '@linux-odyssey/models'
function loginMethods(user) {
const methods = []
@@ -12,10 +12,14 @@ export function userCount() {
return User.find().count()
}
export async function userList({ nextKey, itemsPerPage }) {
const key = new mongoose.Types.ObjectId(nextKey)
// const matchStage = nextKey ? { user: { $gt: key } } : {}
const matchStage = nextKey ? { user: { $gt: key } } : {}
export async function userList({ nextKey, itemsPerPage, order }) {
console.log(order)
let matchStage = {}
if (nextKey) {
const key = new mongoose.Types.ObjectId(nextKey)
matchStage = { user: order.matchStage(key) }
}
console.log(matchStage)
const users = await Session.aggregate([
{
$match: matchStage,
@@ -36,7 +40,7 @@ export async function userList({ nextKey, itemsPerPage }) {
},
},
{ $unwind: '$userData' },
{ $sort: { 'userData._id': 1 } },
{ $sort: { 'userData._id': order.order() } },
{ $limit: itemsPerPage },
])