This repository has been archived by the owner on Jun 19, 2021. It is now read-only.
/
mongodb.js
815 lines (636 loc) · 17.5 KB
/
mongodb.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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
/**
@module drivers
@namespace driver
*/
var _ = require('underscore'),
util = require('util'),
slice = Array.prototype.slice,
mongodb = protos.requireDependency('mongodb', 'MongoDB Driver'),
Db = mongodb.Db,
Server = mongodb.Server,
ObjectID = mongodb.ObjectID,
Collection = mongodb.Collection,
EventEmitter = require('events').EventEmitter;
/**
MongoDB Driver class
@class MongoDB
@extends Driver
@constructor
@param {object} app Application instance
@param {object} config Driver configuration
*/
function MongoDB(app, config) {
var self = this;
this.events = new EventEmitter();
config = protos.extend({
host: 'localhost',
port: 27017,
database: 'default',
storage: null,
username: '',
password: '',
safe: true
}, config || {});
if (typeof config.port != 'number') config.port = parseInt(config.port, 10);
this.className = this.constructor.name;
this.app = app;
app.debug(util.format('Initializing MongoDB for %s:%s', config.host, config.port));
/**
Driver configuration
config: {
host: 'localhost',
port: 27017,
database: 'db_name',
storage: 'redis'
}
@property config
@type object
*/
this.config = config;
var reportError = function(err) {
app.log(util.format("MongoDB [%s:%s] %s", config.host, config.port, err));
self.client = null;
}
// Set db
self.db = new Db(config.database, new Server(config.host, config.port, {}), {safe: config.safe});
// Add async task
app.addReadyTask();
// Get client
self.db.open(function(err, client) {
if (err) {
reportError(err);
} else {
// Set client
self.client = client;
// Set storage
if (typeof config.storage == 'string') {
self.storage = app.getResource('storages/' + config.storage);
} else if (config.storage instanceof protos.lib.storage) {
self.storage = config.storage;
}
// Authenticate
if (config.username && config.password) {
self.db.authenticate(config.username, config.password, function(err, success) {
if (err) {
var msg = util.format('MongoDB: unable to authenticate %s@%s', config.username, config.host);
app.log(new Error(msg));
throw err;
} else {
// Emit initialization event
self.events.emit('init', self.db, self.client);
}
});
} else {
// Emit initialization event
self.events.emit('init', self.db, self.client);
}
}
});
// Flush async task
this.events.once('init', function() {
app.flushReadyTask();
});
// Only set important properties enumerable
protos.util.onlySetEnumerable(this, ['className', 'db']);
}
util.inherits(MongoDB, protos.lib.driver);
/**
Inserts values into a collection
Example:
mongodb.insertInto({
collection: 'users',
values: {user: 'hello', pass: 'passme'}
}, function(err, docs) {
console.log([err, docs]);
});
@method insertInto
@param {object} o
@param {function} callback
*/
MongoDB.prototype.insertInto = function(o, callback) {
var self = this,
collection = o.collection,
values = o.values;
if (!values) {
callback.call(self, new Error("MongoDB::insertInto: 'values' is missing"));
return;
}
this.client.collection(collection, function(err, collection) {
if (err) callback.call(self, err);
else {
collection.insert(values, function(err, docs) {
callback.call(self, err, docs);
});
}
});
}
/**
Updates items where condition is satisfied
Example:
mongodb.updateWhere({
collection: 'users',
condition: {user: 'user1},
multi: true,
values: {pass: 'pass1'}
}, function(err) {
console.log(err);
});
@method updateWhere
@param {object} o
@param {function} callback
*/
MongoDB.prototype.updateWhere = function(o, callback) {
var self = this,
collection = o.collection || '',
condition = o.condition,
multi = (typeof o.multi == 'undefined') ? true : (o.multi || false), // Ensure boolean
values = o.values || {};
if (!o.condition) {
callback.call(self, new Error("MongoDB::queryWhere: 'condition' is missing"));
return;
}
this.client.collection(collection, function(err, collection) {
if (err) callback.call(self, err);
else {
collection.count(condition, function(err, count) {
if (err) callback.call(self, err);
else {
collection.update(condition, {$set: values}, {multi: multi, upsert: false}, function(err) {
// Note: upsert is set to false, to provide predictable results
callback.call(self, err || null);
});
}
});
}
});
}
/**
Updates items by ID
Example:
mongodb.updateById({
_id: 1,
collection: 'users',
values: {pass: 'pass1'}
}, function(err) {
console.log(err);
});
mongodb.updateById({
_id: [1, 2],
collection: 'users',
values: {pass: 'pass1'}
}, function(err) {
console.log(err);
});
@method updateById
@param {object} o
@param {function} callback
*/
MongoDB.prototype.updateById = function(o, callback) {
var self = this,
collection = o.collection || '',
values = o.values || {};
if (typeof o._id == 'undefined') {
callback.call(self, new Error("MongoDB::updateById: '_id' is missing"));
return;
}
var condition = constructIdCondition(o._id);
this.updateWhere({
collection: collection,
condition: condition,
multi: o.multi,
values: values
}, callback);
}
/**
Deletes items where condition is satisfied
Example:
mongodb.deleteWhere({
collection: 'users',
condition: {user: 'user1}
}, function(err) {
console.log(err);
});
@method deleteWhere
@param {object} o
@param {function} callback
*/
MongoDB.prototype.deleteWhere = function(o, callback) {
var self = this,
collection = o.collection || '',
condition = o.condition;
if (!condition) {
callback.call(self, new Error("MongoDB::deleteWhere: 'condition' is missing"));
return;
}
this.client.collection(collection, function(err, collection) {
if (err) callback.call(self, err);
else {
collection.remove(condition, function(err) {
if (err) callback.call(self, err);
else callback.call(self, null);
});
}
});
}
/**
Deletes records by ID
Example:
mongodb.deleteById({
_id: 1,
collection: 'users'
}, function(err) {
console.log(err);
});
mongodb.deleteById({
_id: [1, 2],
collection: 'users'
}, function(err) {
console.log(err);
});
@method deleteById
@param {object} o
@param {function} callback
*/
MongoDB.prototype.deleteById = function(o, callback) {
var self = this,
collection = o.collection || '';
if (!o._id) {
callback.call(self, new Error("MongoDB::deleteById: '_id' is missing"));
return;
}
var args = {
collection: collection,
condition: constructIdCondition(o._id)
}
this.deleteWhere(args, callback);
}
/**
Queries documents where condition is satisfied
Example:
mongodb.queryWhere({
collection: 'users',
condition: {'user': 'user1},
fields: {'user': 1, 'pass': 1}
}, function(err, docs) {
console.log([err, docs]);
});
@method queryWhere
@param {object} o
@param {function} callback
*/
MongoDB.prototype.queryWhere = function(o, callback) {
var self = this,
collection = o.collection || '',
fields = o.fields || {},
condition = o.condition,
_id = (condition && condition._id);
if (!condition) {
callback.call(self, new Error("MongoDB::queryWhere: 'condition' is missing"));
return;
}
// If _id is passed other conditions will be ignored
if (_id != null) condition = constructIdCondition(_id);
this.client.collection(collection, function(err, collection) {
if (err) callback.call(self, err);
else {
collection.__find(condition, fields, function(err, docs) {
callback.call(self, err, docs);
});
}
});
};
/**
Queries documents by ID
Example:
mongodb.queryById({
_id: 1,
collection: 'users',
fields: {'user': 1, 'pass': 1}
}, function(err, docs) {
console.log([err, docs]);
});
mongodb.queryById({
_id: [1, 2],
collection: 'users',
fields: {'user': 1, 'pass': 1}
}, function(err, docs) {
console.log([err, docs]);
});
@method queryById
@param {object} o
@param {function} callback
*/
MongoDB.prototype.queryById = function(o, callback) {
var self = this,
collection = o.collection || '',
fields = o.fields || {};
if (typeof o._id == 'undefined') {
callback.call(self, new Error("MongoDB::queryById: '_id' is missing"));
return;
}
var condition = constructIdCondition(o._id);
this.client.collection(collection, function(err, collection) {
if (err) callback.call(self, err);
else {
collection.__find(condition, fields, function(err, docs) {
callback.call(self, err, docs);
});
}
});
};
/**
Queries all documents in a collection
Example:
mongodb.queryAll({
collection: 'users',
fields: {'user': 1, 'pass': 1}
}, function(err, docs) {
console.log([err, docs]);
});
@method queryAll
@param {object} o
@param {function} callback
*/
MongoDB.prototype.queryAll = function(o, callback) {
var self = this,
collection = o.collection || '',
fields = o.fields || {};
var args = {
collection: collection,
fields: fields,
condition: {}
}
this.queryWhere(args, callback);
};
/**
Queries documents by ID, returning an object with the ID's as keys,
which contain the document (if found), or null if the document is not found.
Example:
mongodb.idExists({
_id: 1,
collection: 'users'
}, function(err, docs) {
console.log([err, docs]);
});
mongodb.idExists({
_id: [1, 2],
collection: 'users',
fields: {user: 1, pass: 1}
}, function(err, docs) {
console.log([err, docs]);
});
@method idExists
@param {object} o
@param {function} callback
*/
MongoDB.prototype.idExists = function(o, callback) {
var self = this,
collection = o.collection || '',
fields = o.fields || {},
_id = o._id;
if (typeof _id == 'undefined') {
callback.call(self, new Error("MongoDB::idExists: '_id' is missing"));
return;
}
var args = {
collection: collection,
fields: fields,
_id: _id
}
this.queryById(args, function(err, docs) {
if (err) callback.call(self, err, {});
else {
var out = {}, doc, id, i;
// Store found docs
for (i=0; i < docs.length; i++) {
doc = docs[i];
out[doc._id.toString()] = doc;
}
// Set missing docs as null
for (i=0; i < _id.length; i++) {
id = _id[i];
if (! (id in out)) out[id] = null;
}
callback.call(self, null, out);
}
});
};
/**
Counts all documents in a collection
Example:
mongodb.count({
collection: 'users'
}, function(err, count) {
console.log([err, count]);
});
@method count
@param {object} o
@param {function} callback
*/
MongoDB.prototype.count = function(o, callback) {
var self = this,
collection = o.collection || '';
this.client.collection(collection, function(err, collection) {
if (err) callback.call(self, err);
else {
collection.count(function(err, count) {
callback.call(self, err, count);
});
}
});
}
/**
Converts `_id` to `id` when generating model objects,
to conform with the Model API.
Used internally by the model.
@private
@method idFilter
@param {object} o
*/
MongoDB.prototype.idFilter = function(o) {
if ('_id' in o) {
o.id = o._id;
delete o._id;
}
}
// Model methods. See lib/driver.js for Model API docs
MongoDB.prototype.__modelMethods = {
/* Model API insert */
insert: function(o, callback) {
var self = this;
// Validate,
var err = this.validateProperties(o);
if (err) callback.call(self, err);
else {
// Convert object types to strings
this.convertTypes(o);
// Set model defaults
this.setDefaults(o);
// Convert `id` to `_id`
convertMongoID(o);
// Save data into the database
this.driver.insertInto({
collection: this.context,
values: o
}, function(err, docs) {
if (err) callback.call(self, err, null);
else {
callback.call(self, null, docs[0]._id);
}
});
}
},
/* Model API get */
get: function(o, callback) {
var self = this;
if (typeof o == 'number' || typeof o == 'string' || o instanceof ObjectID) {
// If `o` is number: Convert to object
o = {_id: o};
} else if (o instanceof Array) {
// If `o` is an array of params, process args recursively using multi
var arr = o,
multi = this.multi();
for (var i=0; i < arr.length; i++) {
multi.get(arr[i]);
}
multi.exec(function(err, docs) {
callback.call(self, err, docs);
});
return;
} else if (o.constructor === Object) {
// IF `o` is object: Validate without checking required fields
this.propertyCheck(o);
} else {
callback.call(self, new Error(util.format("%s: Wrong value for `o` argument", this.className)), null);
return;
}
// TODO: automatically detect which fields should be retrieved based
// on this.properties
this.driver.queryWhere({
collection: this.context,
condition: o,
fields: {}
}, function(err, docs) {
if (err) callback.call(self, err, null);
else {
if (docs.length === 0) callback.call(self, null, []);
else {
for (var models=[],i=0; i < docs.length; i++) {
models.push(self.createModel(docs[i]));
}
callback.call(self, null, models);
}
}
});
},
/* Model API getAll */
getAll: function(callback) {
var self = this;
this.driver.queryAll({
collection : this.context
}, function(err, docs) {
if (err) callback.call(self, err, null);
else {
for (var models=[],i=0; i < docs.length; i++) {
models.push(self.createModel(docs[i]));
}
callback.call(self, null, models);
}
});
},
/* Model API save */
save: function(o, callback) {
var self = this;
// Note: Validation has already been performed by ModelObject
// Convert `id` to `_id`
convertMongoID(o);
// Get _id, and prepare update data
var _id = o._id;
delete o._id;
if (typeof _id == 'undefined') {
callback.call(this, new Error("Unable to update model object without ID"));
return;
}
// Validate, throw error on failure
var err = this.validateProperties(o, {noRequired: true});
if (err) callback.call(self, err);
else {
this.driver.updateById({
_id: _id,
collection: this.context,
values: o
}, function(err, docs) {
callback.call(self, err);
});
}
},
/* Model API delete */
delete: function(id, callback) {
var self = this;
if (typeof id == 'number' || typeof id == 'string' || id instanceof Array || id instanceof ObjectID) {
this.driver.deleteById({
collection: this.context,
_id: id
}, function(err) {
callback.call(self, err);
});
} else {
callback.call(self, new Error(util.format("%s: Wrong value for `id` parameter", this.className)));
}
}
}
/*
Construct Id condition
Provides: {object} condition
@private
@param {number|string|array} _id
*/
function constructIdCondition(_id) {
if (typeof _id === 'number' || _id instanceof ObjectID || _id.constructor === Object) {
// Number or ObjectID/Object instance » Return as is
return {_id: _id};
} else if (typeof _id === 'string') {
// String » Convert to Object ID
return {_id: new ObjectID(_id)};
} else if (_id instanceof Array) {
// Array » Return $in condition
for (var id, $in=[], i=0; i < _id.length; i++) {
id = _id[i];
if (typeof id == 'number' || id instanceof ObjectID) {
$in.push(id);
} else if (typeof id == 'string') {
$in.push(new ObjectID(id));
}
}
return {_id: {$in: $in}};
}
}
/*
Converts an 'id' param to an _id param
@private
@param {number|string|array} _id
*/
function convertMongoID(o) {
if ('id' in o) {
o._id = o.id;
delete o.id;
}
}
/*
Quick find method without cursors
*/
Collection.prototype.__find = function() {
var self = this,
args = slice.call(arguments, 0),
callback = args.pop();
args.push(function(err, cursor) {
if (err) callback.call(self, err);
else {
cursor.toArray(function(err, docs) {
callback.call(self, err, docs);
});
}
});
this.find.apply(this, args);
}
module.exports = MongoDB;