目前透過 mongoose 查詢 pagination 資料覺得很麻煩,
先取得 total count 再取 page data,
目前使用的方式如下:
user .find(where) .count() .then((totalCount) => { if (totalCount && totalCount > 0) { return user.find(where) .select('field1 field2 field3 filed4') .sort({ createdOn: -1 }) .skip(skip) .limit(limit) .exec() .then((rows) => { return { rows:rows totalCount: totalCount }); } else { return res.status(200) .json({ rows: [], skip: skip, limit: limit, totalCount: 0 }) .end(); } }) .then((result) => { return res.status(200) .json({ rows: result.rows, skip: skip, limit: limit, totalCount: result.totalCount }) .end(); }) .catch((err) => { next(err); });
寫得落落長,太麻煩了,花了一些時間查查,有沒有什麼方便的方式
原來 mongoose 有 pagination plugin 可以用,真的是佛心來的,
使用方式如下:
Installation:
npm install mongoose-paginate
Usage:
var mongoose = require('mongoose'); var mongoosePaginate = require('mongoose-paginate'); var schema = new mongoose.Schema({ /* schema definition */ }); schema.plugin(mongoosePaginate); var Model = mongoose.model('Model', schema); // Model.paginate() Model.paginate([query], [options], [callback])
所以上面的範例可以改成:
var where = {}; var options = { select: 'field1 field2 field3 filed4', sort: { createdOn: -1 }, lean: true, offset: 20, limit: 10 }; user.paginate(where, options).then(function(result) { return res.status(200) .json({ rows: result.docs, skip: skip, limit: limit, totalCount: result.total }) .end() });
太好了,是不是簡單很多!
reference:https://www.npmjs.com/package/mongoose-paginate
沒有留言:
張貼留言