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

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>),好了下面开始说正事:


需求场景

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

数据库如下

作者Author

// author
let authorSchema = new Schema({
  name: {
    type: String,
    required: true,
    index: true,
    unique: true
  }
})
module.exports = mongoose.model('Author', authorSchema)

书籍Book

// book
let bookSchema = new Schema({
  author: {
    type: Schema.Types.ObjectId,
    ref: 'Author'
  },
  type: {
    type: String,
    default: ''
  }
})
module.exports = mongoose.model('Book', bookSchema)

查询如下

// 获取列表-不分组
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
  }
}

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


// 获取列表-如何分组
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
  }
}
###

countDocuments也是可以筛选的
参数传递下查询条件就ok了

let total = await Book.countDocuments({ author: authorId }) 

郑重声明:本站部分内容转载自网络,版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们(QQ/微信153890879)修改或删除,多谢。