-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
696 lines (649 loc) · 14.1 KB
/
index.js
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
/*
Name:vitex
Author:skipify
Version:0.0.10
Email:skipify@qq.com
*/
var mongodb = require('mongodb'),
ObjectID = mongodb.ObjectID,
mongodbConfig,
_ = require('underscore');;
_mdcache = {}; //链接缓存 global
var mongoOptions = {
"server" : {
"poolSize" : 10
}
};
/*
opt @param string/object
string collection
object
*/
var Model = function(dc,opt){
if(!(this instanceof Model))
{
return new Model(dc,opt);
}
if(_.isObject(dc))
{
dc = '';
opt = dc;
}
this.countConfig = {};//方便find之后使用count查询,会缓存一次查询条件
this._dc = dc;//持久保存的集合名字,不会因为查询完毕而丢失当不指定from的时候会自动应用dc
this.autoInc = opt.autoInc === undefined ? true :opt.autoInc;
if(opt.file){
var setting = require(opt.file);
mongodbConfig = setting;
}
if(opt.mongodb)
{
mongodbConfig = opt.mongodb;
}
if(!mongodbConfig || mongodbConfig.length == 0)
{
throw new Error('No Connect Config found');
}
//创建数据库连接
this.connect = createConnect(connectString(mongodbConfig));
/*
初始化信息
*/
this._config = {
collection:'',
where:{},
fields:{},
limit:0,
skip:0,
sort:{},
set : {}
};
return this;
}
/*
输出查询配置信息
*/
Model.prototype.test = function(){
console.log(this._config);
return this;
}
/*
设置当前模型永不过期的集合名称
此方法设置的集合名称不会因为查询而被清除
*/
Model.prototype.endureCollection = function( c ){
this._dc = c;
return this;
}
/*
链接数据库
db config.js中的配置格式
*/
var connectString = function(dbs){
var url = '';
if(!dbs)
{
throw new Error('Can not find Connect config,please set setting or settingFile option');
}
if(!_.isArray(dbs))
{
dbs = [dbs];
}
if(dbs.length == 1){
//单数据库
db = dbs[0];
url = 'mongodb://' + (db.username ? db.username + ':' + db.password + '@': '')
+ db.host + ':' + db.port + '/' + db.database;
}else{
//集群
var urls = [];
dbs.forEach(function(db,k){
urls[k] = (db.username ? db.username + ':' + db.password + '@': '') + db.host + ':' + db.port;
})
url = 'mongodb://' + urls.join(',') + '/' + dbs[0].database + '?replicaSet=' + dbs[0].replicaSet;
}
return url;
}
/*
链接到数据库
cnodejs.org
*/
function createConnect (url) {
var fns = [], status = 0, _db = _mdcache[url];
return function (f) {
var args = arguments;
if (_db !== null && typeof _db === 'object') {
f.call(null, _db);
return;
}
fns.push(f);
// 当有一个连接初始化请求时,挂起其他初始化请求
// 连接池建立完后,使用该连接处理挂起的请求
if (status === 0) {
status = 1;
mongodb.MongoClient.connect(url, mongoOptions, function (err, db) {
if (err) {
//更友好的错误处理。。。
throw new Error('Can not connect to mongodb server' + url);
}
_db = _mdcache[url] = db;
for (var i = 0, len = fns.length; i < len; i++) {
fns.shift().call(null, _db);
}
});
}
};
}
Model.prototype.resetConfig = function(){
var def = {
collection : "",
where : {},
fields : {},
limit : 0,
skip : 0,
sort : {},
set : {}
};
for(var i in def)
{
this._config[i] = def[i]
}
if(this._dc){
this._config.collection = this._dc;
}
return this;
}
/*
设置查询条件
*/
Model.prototype.where = function(k,v){
if(k == "_id")
{
if(this.autoInc)
{
v = parseInt(v);
}else{
v = new ObjectID(v);
}
}
if(_.isObject(k)){
this._config.where = _.extend(this._config.where,k);
}else{
this._config.where[k] = v;
}
return this;
}
/*
模糊查询
@param string
@param string/regexp
*/
Model.prototype.like = function(key,val){
if(_.isRegExp(val))
{
this.where(key,val);
}else{
this.where(key,{ $regex: val });
}
return this;
}
/*
选择集合
*/
Model.prototype.from = function(collection){
this._config.collection = collection;
return this;
}
/*
查询的字段
field string/object/array
_id
{name:1,email:1}
[name,email]
*/
Model.prototype.select = function(field){
var _fields = {};
if(_.isArray(field)){
field.forEach(function(f){
_fields[f] = 1;
});
}else if(_.isObject(field)){
_fields = field;
}else{
_fields[field] = 1;
}
this._config.fields = _.extend(this._config.fields,_fields);
return this;
}
/*
限制条数
limit 限制条数
skip 跳过的条数
*/
Model.prototype.limit = function(limit,skip){
this._config.skip = (skip === undefined ? 0 : skip);
this._config.limit = (limit == undefined ? 0 : limit);
return this;
}
/*
排序
obj 排序字段
{age:1,step:-1}
*/
Model.prototype.sort = function(obj){
this._config.sort = obj;
return this;
}
/*
设置要修改的字段
*/
Model.prototype.set = function(k,v){
if(_.isObject(k)){
for(var i in k){
this._config.set[i] = k[i];
}
}else{
this._config.set[k] = v;
}
return this;
}
/*
查询
callback
explain 是否输出查询explain信息
*/
Model.prototype.find = function(callback,explain){
var _c = _.defaults({},this._config);
_c.collection = _c.collection || this._dc,
that = this;
this.connect(function(db){
var opt = {};
if(_c.skip){
opt.skip = _c.skip;
}
if(_c.limit){
opt.limit = _c.limit;
}
if(_c.fields){
opt.fields = _c.fields;
}
if(_c.sort){
opt.sort = _c.sort;
}
if(!_c.collection){
throw new Error('No Collection specified');
}
var col = db.collection(_c.collection);
if(explain){
col.find(_c.where,opt).explain(function(err,explaination){
console.log('Explain Info:');
console.log(explaination);
console.log('End Explain Info');
});
}
col.find(_c.where,opt).toArray(function(err,docs){
callback.apply(null,arguments)
});
that.countConfig = {where:_c.where,collection:_c.collection};
//重置参数
that.resetConfig();
});
}
/*
findone
*/
Model.prototype.findOne = function(callback,explain){
var _c = _.defaults({},this._config);
_c.collection = _c.collection || this._dc,
that = this;
this.connect(function(db){
var opt = {};
if(_c.fields){
opt.fields = _c.fields;
}
if(_c.sort){
opt.sort = _c.sort;
}
if(!_c.collection){
throw new Error('No Collection specified');
}
var col = db.collection(_c.collection);
if(explain){
col.find(_c.where,opt).explain(function(err,explaination){
console.log('Explain Info:');
console.log(explaination);
console.log('End Explain Info');
});
}
col.findOne(_c.where,opt,function(err,doc){
callback.apply(null,arguments)
});
//重置参数
that.resetConfig();
});
}
/*
统计数量
*/
Model.prototype.count = function(callback){
var _c = _.defaults({},this._config),
that = this;
_c.collection = _c.collection || this._dc;
this.connect(function(db){
var collection = _c.collection || that.countConfig.collection;
var where = _.isEmpty(_c.where) ? that.countConfig.where : _c.where;
if(!collection){
throw new Error('No Collection specified');
}
var col = db.collection(collection);
col.count(where,function(err,count){
callback.apply(null,arguments);
})
that.countConfig = {};
});
}
/*
删除
*/
Model.prototype.remove = function(opt,callback){
if(_.isFunction(opt)){
callback = opt;
opt = {w:1};
}
var _c = _.defaults({},this._config);
_c.collection = _c.collection || this._dc;
this.connect(function(db){
db.collection(_c.collection).deleteMany(_c.where,opt,function(err,result){
callback !== undefined ? callback.apply(null,arguments):'';
});
});
//重置参数
this.resetConfig();
}
/*
removeone
*/
Model.prototype.removeOne = function(opt,callback){
if(_.isFunction(opt)){
callback = opt;
opt = {w:1};
}
var _c = _.defaults({},this._config);
_c.collection = _c.collection || this._dc;
this.connect(function(db){
db.collection(_c.collection).deleteOne(_c.where,opt,function(err,result){
callback !== undefined ? callback.apply(null,arguments):'';
});
});
//重置参数
this.resetConfig();
}
/*
添加数据
*/
Model.prototype.save = function(doc,opt,callback){
if(_.isFunction(opt)){
callback = opt;
opt = {w:1};
}
var _c = _.defaults({},this._config);
_c.collection = _c.collection || this._dc,
that = this;
this.connect(function(db){
var insert = function(doc){
if(_.isArray(doc))
{
db.collection(_c.collection).insertMany(doc,opt,function(err,result){
callback !== undefined ? callback.apply(null,arguments):'';
});
}else{
db.collection(_c.collection).save(doc,opt,function(err,result){
callback !== undefined ? callback.apply(null,arguments):'';
});
}
}
if(that.autoInc)
{
if(_.isArray(doc))
{
var total = doc.length;
that.autoIncId(total,function(id){
for(var i=0;i<total;i++ )
{
doc[i]._id = (id + i)
}
insert(doc);
});
}else{
that.autoIncId(function(id){
doc._id = id;
insert(doc);
});
}
}else{
insert(doc);
}
});
//重置参数
this.resetConfig();
}
/*
修改
{opt} 多个参数 multi
*/
Model.prototype.update = function(doc,opt,callback){
if(_.isFunction(opt)){
callback = opt;
opt = {w:1};
}
var _c = _.defaults({},this._config);
_c.collection = _c.collection || this._dc,
opt = opt || {};
multi = opt.multi || true;
if(opt.multi)
{
delete opt['multi'];
}
//doc
if(!doc || _.isEmpty(doc)){
var _doc = this._config.set;
doc = {$set:_doc};
}
this.connect(function(db){
if(multi)
{
db.collection(_c.collection).updateMany(_c.where,doc,opt,function(err,result){
callback !== undefined ? callback.apply(null,arguments):'';
});
}else{
db.collection(_c.collection).updateOne(_c.where,doc,opt,function(err,result){
callback !== undefined ? callback.apply(null,arguments):'';
});
}
});
//重置参数
this.resetConfig();
}
/*
修改一个
*/
Model.prototype.updateOne = function(doc,opt,callback){
opt.multi = false;
this.update.call(null,doc,opt,callback);
}
/*
按页数查找
我们鼓励页码倒叙排列
callback 参数
@return {total:1,data:docs}
*/
Model.prototype.page = function(page,num,callback){
page = page ? page : 1;
num = num ? num : 20;
var skip = (( page - 1) >=0 ? (page - 1) : 0) * num,
that = this;
this.limit(num,skip);
this.find(function(err,docs){
if(err)
{
callback.apply(null,arguments);
return false;
}
that.count(function(er,count){
if(er)
{
callback.apply(null,arguments);
return false;
}
callback.call(null,null,{total:count,data:docs});
});
})
}
/*
删除集合
*/
Model.prototype.dropCollection = function(name,callback){
var that = this;
this.connect(function(db){
db.dropCollection(name,function(err,result){
callback != undefined ? callback.apply(null,arguments) : '';
//如果是自增的则清空自增列表
if(that.isAutoInc)
{
db.collection('autoIncIds').update({'_id':name},{$set:{val:0}},{w:1,upsert:true},function(err,result){
if(err){
throw new Error('clear autoInc Number Error');
}
})
}
});
});
}
//步增
Model.prototype.step = function(field,step,callback){
if(typeof step === 'function'){
callback = step;
step = null;
}
step = step || 1;
var obj = {};
obj[field] = step;
this.update({$inc:obj},callback);
}
/*
关闭连接
*/
Model.prototype.close = function(){
this.connect(function(db){
for(var m in _mdcache){
if(_mdcache[m] == db){
delete _mdcache[m];
break;
}
}
db.close();
});
}
/*
方便操作的快捷方式
*/
/*
按照ID查找
*/
Model.prototype.findById = function(id,callback){
//id = new ObjectID(id);
this.where({_id:id});
this.findOne(callback);
}
/*
按照ID删除
*/
Model.prototype.removeById = function(id,callback){
//id = new ObjectID(id);
this.where({_id:id});
this.removeOne(callback);
}
/*
获取当前操作的操作配置
*/
Model.prototype.getConfig = function(){
return this._config;
}
/*
清空持久化的集合名称
*/
Model.prototype.clearEndureCollection = function(){
this._dc = '';
return this;
}
/*
设置是否需要自增ID
*/
Model.prototype.isAutoInc = function(b){
this.autoInc = b;
return this;
}
/*
生成一个自增的ID
1,c
c
*/
Model.prototype.autoIncId = function(c,step,callback)
{
if(_.isFunction(step))
{
callback = step;
step = 1;
}
if(_.isFunction(c))
{
callback = c;
c = null;
step = 1;
}
if(_.isNumber(c))
{
step = c;
c = null;
}
c = c ? c : (this._config.collection ? this._config.collection : this._dc);
step = step ? step : 1;
if(!c){
throw new Error('can not find collection for autoIncrement');
}
this.connect(function(db){
db.collection('autoIncIds').findAndModify({_id:c},{},{$inc:{val:step}},{w:1,upsert:true},function(err,doc){
if(err)
{
throw new Error('cant not create auto increment id');
}
if(!doc.value.val)
{
callback.call(null,1);
}else{
callback.call(null,(doc.value.val + 1));
}
});
});
}
/*
test:
一个mongodb的简单封装
model.exec(function(db){
db.collection('test').ensureIndex('ee',{step:1},function(err,indexName){
console.log(indexName);
})
db 可以使用
});
*/
Model.prototype.exec = function(callback){
this.connect(function(db){
console.log(arguments);
callback.apply(null,arguments);
});
}
/*
引入的mongodb对象
*/
Model.mongodb = mongodb;
module.exports = Model;