gpt4 book ai didi

node.js - json数组中的 Node 分页

转载 作者:太空宇宙 更新时间:2023-11-04 01:41:07 24 4
gpt4 key购买 nike

我已经实现了以下分页代码,但无法使其工作。我需要使用以下 json 数据来完成它:

以下代码适用于Vt.js文件

const express = require('express');
const app = express();
const cors = require('cors');
var MongoClient = require('mongodb').MongoClient;
app.use(cors())
var url = "mongodb://localhost:27017/";

var pagination = require('pagination');
var paginator = pagination.create('search', {
prelink: '/users',
current: 2,
rowsPerPage: 2,
totalResult: 10020
});
console.log(paginator.render());

app.get('/users', function(req, res) {

MongoClient.connect(url, function(err, db) {
if (err)
throw err;
var dbo = db.db("MyNewDatabase");
var data = dbo.collection("VirtualCapitalDB").find({}).toArray(function(err, result) {
if (err)
throw err;
console.log(result);
res.json(result);

db.close();
});
});
})

app.listen(8080, ()=>console.log('Listening on port 8080'));

一旦你不分页访问它,你就可以获得以下 json 数组

[{
"_id": "5bcb3c77dc56e939187c13a5",
"firstname": "dumindu",
"lastname": "nagasinghe",
"videocount": 5
}, {
"_id": "5bcb3ce6dc56e939187c13a9",
"firstname": "cha",
"lastname": "advv",
"videocount": 10
}, {
"_id": "5bcb3d4bdc56e939187c13ab",
"firstname": "dvvs",
"lastname": "scvssv",
"videocount": 4
}, {
"_id": "5bcb3d7adc56e939187c13ac",
"firstname": "advav",
"lastname": "dvdvv",
"videocount": 5
}, {
"_id": "5bcb40f7a768f83918480a2b",
"firstname": "advav",
"lastname": "dvdvv",
"videocount": 5
}, {
"_id": "5bcb4103a768f83918480a2c",
"firstname": "advav",
"lastname": "dvdvv",
"videocount": 5
}, {
"_id": "5bcb4106a768f83918480a2d",
"firstname": "advav",
"lastname": "dvdvv",
"videocount": 5
}, {
"_id": "5bcb4125a768f83918480a2e",
"firstname": "advav",
"lastname": "dvdvv",
"videocount": 5
}]

但我需要添加分页并获取单页的 2 个数据对象。如何在代码中实现它?

最佳答案

编写数组项分页的最佳方法

paginator(items, page, per_page) {

var page = page || 1,
per_page = per_page || 10,
offset = (page - 1) * per_page,

paginatedItems = items.slice(offset).slice(0, per_page),
total_pages = Math.ceil(items.length / per_page);
return {
page: page,
per_page: per_page,
pre_page: page - 1 ? page - 1 : null,
next_page: (total_pages > page) ? page + 1 : null,
total: items.length,
total_pages: total_pages,
data: paginatedItems
};
}

关于node.js - json数组中的 Node 分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52911270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com