feat: change to nextKey in users

This commit is contained in:
Chen, Tai-Lin committed 2023-12-13 14:40:47 +08:00
1 parent 3e7092dbd6
commit 1b94ae75ca
3 files changed
+20 -14

No files matched your search

+8 -5
View File
@@ -1,20 +1,23 @@
import { userList, userCount } from '../models/users.js'
export async function userListController(req, res) {
const pageNumber = req.query.page || 1
const { nextKey } = req.query
const itemsPerPage = 50
try {
const totalUsers = await userCount()
const maxPages = Math.ceil(totalUsers / itemsPerPage)
// const totalUsers = await userCount()
// const maxPages = Math.ceil(totalUsers / itemsPerPage)
const users = await userList(pageNumber, itemsPerPage)
const users = await userList({ nextKey, itemsPerPage })
const newNextKey = users[users.length - 1]?._id
res.render('users', {
users,
maxPages: Array.from({ length: maxPages }, (_, index) => index + 1),
nextKey: newNextKey,
// maxPages: Array.from({ length: maxPages }, (_, index) => index + 1),
})
} catch (error) {
console.error(error)
res.status(500).send('Error fetching user data')
}
}
+11 -6
View File
@@ -1,4 +1,5 @@
import { Session, User } from '@linux-odyssey/models'
import mongoose from 'mongoose'
function loginMethods(user) {
const methods = []
@@ -11,10 +12,14 @@ export function userCount() {
return User.find().count()
}
export async function userList(pageNumber, itemsPerPage) {
const skipAmount = (pageNumber - 1) * itemsPerPage
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 } } : {}
const users = await Session.aggregate([
{
$match: matchStage,
},
{
$group: {
_id: '$user',
@@ -31,14 +36,14 @@ export async function userList(pageNumber, itemsPerPage) {
},
},
{ $unwind: '$userData' },
{ $sort: { 'userData.createdAt': 1 } },
{ $skip: skipAmount },
{ $sort: { 'userData._id': 1 } },
{ $limit: itemsPerPage },
])
return users.map(({ userData, count, lastActivityAt }) => {
const { username, email, createdAt } = userData
const { _id, username, email, createdAt } = userData
return {
_id,
username,
email,
createdAt: createdAt?.toLocaleString(),
+1 -3
View File
@@ -22,7 +22,5 @@
</table>
</div>
<div class='pagination'>
{{#each maxPages}}
<a href='/users?page={{this}}'>{{this}}</a>
{{/each}}
<a href='/users?nextKey={{nextKey}}'>Next</a>
</div>