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

新手上路,请多包涵

需求场景

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

数据库如下

作者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
  }
}
阅读 2.6k
1 个回答

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

let total = await Book.countDocuments({ author: authorId }) 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题