热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

【问Mongoose】我应该如何处理分页?

需求场景作者和书籍列表展示列表时如何处理分页数据库如下

需求场景

作者和书籍列表
展示列表时如何处理分页


数据库如下


作者Author

1
2
3
4
5
6
7
8
9
10
// author

let authorSchema = new Schema({

  name: {

    type: String,

    required: true,

    index: true,

    unique: true

  }

})

module.exports = mongoose.model('Author', authorSchema)


书籍Book

1
2
3
4
5
6
7
8
9
10
11
12
// book

let bookSchema = new Schema({

  author: {

    type: Schema.Types.ObjectId,

    ref: 'Author'

  },

  type: {

    type: String,

    default: ''

  }

})

module.exports = mongoose.model('Book', bookSchema)


查询如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 获取列表-不分组

const getBooks = async (ctx, next) => {

  let { size = 10, page = 1 } = ctx.query

  let optiOns= {

    skip: Number((page - 1) * size),

    limit: Number(size)

  }

  let res = await Book.find({}, null, options)

  let total = await Book.countDocuments()

  let data = {

    list: res,

    pagination: {

      total,

      page,

      size

    }

  }

  ctx.body = {

    data,

    code: 0

  }

}


问题:如果我想得到某个作者的书籍列表,有什么好的解决办法么?



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 获取列表-如何分组

const getMyBooks = async (ctx, next) => {

  let authorId = ctx.authorId

  let { size = 10, page = 1 } = ctx.query

  let optiOns= {

    skip: Number((page - 1) * size),

    limit: Number(size)

  }

  let res = await Book.find({ author: authorId }, null, options)

  // ???????????

  let total = await Book.countDocuments() // 这个总数应该如何获取比较好?是按authorId查到全部的book,取数组length么?

  let data = {

    list: res,

    pagination: {

      total,

      page,

      size

    }

  }

  ctx.body = {

    data,

    code: 0

  }

}



   



推荐阅读
author-avatar
佩菱淑华7
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有