-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
46 lines (40 loc) · 1.28 KB
/
db.js
File metadata and controls
46 lines (40 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Created by chaoningx on 2017/2/27.
*/
const config = require('../../config');
const utils = require('../common/utils');
class DB {
constructor(collectionName) {
this.collection = config.mongodb.dbInstance.collection(collectionName);
this.doc = {};
}
assgin(info) {
return utils.merge(Object.assign({}, this.doc), info);
}
pagination(query, page, pageSize, callback, sortFields, fieldsNeed) {
let collection = this.collection;
collection.count(query, function(err, count) {
if(err) {
callback && callback(err);
return false;
}
let cursor = collection.find(query, fieldsNeed || {});
page = page * 1 || 1;
pageSize = pageSize * 1 || 10;
cursor.sort(sortFields);
cursor.skip(page ? ((page - 1) * pageSize) : (0 * pageSize));
cursor = cursor.limit(pageSize * 1);
cursor.toArray(function(err, items) {
if(err) {
callback && callback(err);
return false;
}
let pageCount = ((count / pageSize) | 0) + (count % pageSize ? 1 : 0);
page = page > pageCount ? pageCount : page;
let rs = { docs: items, page: page, pages: pageCount, limit: pageSize, total: count };
callback && callback(null, rs);
});
});
}
}
module.exports = DB;