forked from Mshuu/nedb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.test.js
executable file
·2876 lines (2393 loc) · 110 KB
/
db.test.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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var should = require('chai').should()
, assert = require('chai').assert
, testDb = 'workspace/test.db'
, fs = require('fs')
, path = require('path')
, _ = require('underscore')
, async = require('async')
, model = require('../lib/model')
, Datastore = require('../lib/datastore')
, Persistence = require('../lib/persistence')
, reloadTimeUpperBound = 60; // In ms, an upper bound for the reload time used to check createdAt and updatedAt
;
describe('Database', function () {
var d;
beforeEach(function (done) {
d = new Datastore({ filename: testDb });
d.filename.should.equal(testDb);
d.inMemoryOnly.should.equal(false);
async.waterfall([
function (cb) {
Persistence.ensureDirectoryExists(path.dirname(testDb), function () {
fs.exists(testDb, function (exists) {
if (exists) {
fs.unlink(testDb, cb);
} else { return cb(); }
});
});
}
, function (cb) {
d.loadDatabase(function (err) {
assert.isNull(err);
d.getAllData().length.should.equal(0);
return cb();
});
}
], done);
});
it('Constructor compatibility with v0.6-', function () {
var dbef = new Datastore('somefile');
dbef.filename.should.equal('somefile');
dbef.inMemoryOnly.should.equal(false);
var dbef = new Datastore('');
assert.isNull(dbef.filename);
dbef.inMemoryOnly.should.equal(true);
var dbef = new Datastore();
assert.isNull(dbef.filename);
dbef.inMemoryOnly.should.equal(true);
});
describe('Autoloading', function () {
it('Can autoload a database and query it right away', function (done) {
var fileStr = model.serialize({ _id: '1', a: 5, planet: 'Earth' }) + '\n' + model.serialize({ _id: '2', a: 5, planet: 'Mars' }) + '\n'
, autoDb = 'workspace/auto.db'
, db
;
fs.writeFileSync(autoDb, fileStr, 'utf8');
db = new Datastore({ filename: autoDb, autoload: true })
db.find({}, function (err, docs) {
assert.isNull(err);
docs.length.should.equal(2);
done();
});
});
it('Throws if autoload fails', function (done) {
var fileStr = model.serialize({ _id: '1', a: 5, planet: 'Earth' }) + '\n' + model.serialize({ _id: '2', a: 5, planet: 'Mars' }) + '\n' + '{"$$indexCreated":{"fieldName":"a","unique":true}}'
, autoDb = 'workspace/auto.db'
, db
;
fs.writeFileSync(autoDb, fileStr, 'utf8');
// Check the loadDatabase generated an error
function onload (err) {
err.errorType.should.equal('uniqueViolated');
done();
}
db = new Datastore({ filename: autoDb, autoload: true, onload: onload })
db.find({}, function (err, docs) {
done(new Error("Find should not be executed since autoload failed"));
});
});
});
describe('Insert', function () {
it('Able to insert a document in the database, setting an _id if none provided, and retrieve it even after a reload', function (done) {
d.find({}, function (err, docs) {
docs.length.should.equal(0);
d.insert({ somedata: 'ok' }, function (err) {
// The data was correctly updated
d.find({}, function (err, docs) {
assert.isNull(err);
docs.length.should.equal(1);
Object.keys(docs[0]).length.should.equal(2);
docs[0].somedata.should.equal('ok');
assert.isDefined(docs[0]._id);
// After a reload the data has been correctly persisted
d.loadDatabase(function (err) {
d.find({}, function (err, docs) {
assert.isNull(err);
docs.length.should.equal(1);
Object.keys(docs[0]).length.should.equal(2);
docs[0].somedata.should.equal('ok');
assert.isDefined(docs[0]._id);
done();
});
});
});
});
});
});
it('Can insert multiple documents in the database', function (done) {
d.find({}, function (err, docs) {
docs.length.should.equal(0);
d.insert({ somedata: 'ok' }, function (err) {
d.insert({ somedata: 'another' }, function (err) {
d.insert({ somedata: 'again' }, function (err) {
d.find({}, function (err, docs) {
docs.length.should.equal(3);
_.pluck(docs, 'somedata').should.contain('ok');
_.pluck(docs, 'somedata').should.contain('another');
_.pluck(docs, 'somedata').should.contain('again');
done();
});
});
});
});
});
});
it('Can insert and get back from DB complex objects with all primitive and secondary types', function (done) {
var da = new Date()
, obj = { a: ['ee', 'ff', 42], date: da, subobj: { a: 'b', b: 'c' } }
;
d.insert(obj, function (err) {
d.findOne({}, function (err, res) {
assert.isNull(err);
res.a.length.should.equal(3);
res.a[0].should.equal('ee');
res.a[1].should.equal('ff');
res.a[2].should.equal(42);
res.date.getTime().should.equal(da.getTime());
res.subobj.a.should.equal('b');
res.subobj.b.should.equal('c');
done();
});
});
});
it('If an object returned from the DB is modified and refetched, the original value should be found', function (done) {
d.insert({ a: 'something' }, function () {
d.findOne({}, function (err, doc) {
doc.a.should.equal('something');
doc.a = 'another thing';
doc.a.should.equal('another thing');
// Re-fetching with findOne should yield the persisted value
d.findOne({}, function (err, doc) {
doc.a.should.equal('something');
doc.a = 'another thing';
doc.a.should.equal('another thing');
// Re-fetching with find should yield the persisted value
d.find({}, function (err, docs) {
docs[0].a.should.equal('something');
done();
});
});
});
});
});
it('Cannot insert a doc that has a field beginning with a $ sign', function (done) {
d.insert({ $something: 'atest' }, function (err) {
assert.isDefined(err);
done();
});
});
it('If an _id is already given when we insert a document, use that instead of generating a random one', function (done) {
d.insert({ _id: 'test', stuff: true }, function (err, newDoc) {
if (err) { return done(err); }
newDoc.stuff.should.equal(true);
newDoc._id.should.equal('test');
d.insert({ _id: 'test', otherstuff: 42 }, function (err) {
err.errorType.should.equal('uniqueViolated');
done();
});
});
});
it('Modifying the insertedDoc after an insert doesnt change the copy saved in the database', function (done) {
d.insert({ a: 2, hello: 'world' }, function (err, newDoc) {
newDoc.hello = 'changed';
d.findOne({ a: 2 }, function (err, doc) {
doc.hello.should.equal('world');
done();
});
});
});
it('Can insert an array of documents at once', function (done) {
var docs = [{ a: 5, b: 'hello' }, { a: 42, b: 'world' }];
d.insert(docs, function (err) {
d.find({}, function (err, docs) {
var data;
docs.length.should.equal(2);
_.find(docs, function (doc) { return doc.a === 5; }).b.should.equal('hello');
_.find(docs, function (doc) { return doc.a === 42; }).b.should.equal('world');
// The data has been persisted correctly
data = _.filter(fs.readFileSync(testDb, 'utf8').split('\n'), function (line) { return line.length > 0; });
data.length.should.equal(2);
model.deserialize(data[0]).a.should.equal(5);
model.deserialize(data[0]).b.should.equal('hello');
model.deserialize(data[1]).a.should.equal(42);
model.deserialize(data[1]).b.should.equal('world');
done();
});
});
});
it('If a bulk insert violates a constraint, all changes are rolled back', function (done) {
var docs = [{ a: 5, b: 'hello' }, { a: 42, b: 'world' }, { a: 5, b: 'bloup' }, { a: 7 }];
d.ensureIndex({ fieldName: 'a', unique: true }, function () { // Important to specify callback here to make sure filesystem synced
d.insert(docs, function (err) {
err.errorType.should.equal('uniqueViolated');
d.find({}, function (err, docs) {
// Datafile only contains index definition
var datafileContents = model.deserialize(fs.readFileSync(testDb, 'utf8'));
assert.deepEqual(datafileContents, { $$indexCreated: { fieldName: 'a', unique: true } });
docs.length.should.equal(0);
done();
});
});
});
});
it("If timestampData option is set, a createdAt field is added and persisted", function (done) {
var newDoc = { hello: 'world' }, beginning = Date.now();
d = new Datastore({ filename: testDb, timestampData: true, autoload: true });
d.find({}, function (err, docs) {
assert.isNull(err);
docs.length.should.equal(0);
d.insert(newDoc, function (err, insertedDoc) {
// No side effect on given input
assert.deepEqual(newDoc, { hello: 'world' });
// Insert doc has two new fields, _id and createdAt
insertedDoc.hello.should.equal('world');
assert.isDefined(insertedDoc.createdAt);
assert.isDefined(insertedDoc.updatedAt);
insertedDoc.createdAt.should.equal(insertedDoc.updatedAt);
assert.isDefined(insertedDoc._id);
Object.keys(insertedDoc).length.should.equal(4);
assert.isBelow(Math.abs(insertedDoc.createdAt.getTime() - beginning), reloadTimeUpperBound); // No more than 30ms should have elapsed (worst case, if there is a flush)
// Modifying results of insert doesn't change the cache
insertedDoc.bloup = "another";
Object.keys(insertedDoc).length.should.equal(5);
d.find({}, function (err, docs) {
docs.length.should.equal(1);
assert.deepEqual(newDoc, { hello: 'world' });
assert.deepEqual({ hello: 'world', _id: insertedDoc._id, createdAt: insertedDoc.createdAt, updatedAt: insertedDoc.updatedAt }, docs[0]);
// All data correctly persisted on disk
d.loadDatabase(function () {
d.find({}, function (err, docs) {
docs.length.should.equal(1);
assert.deepEqual(newDoc, { hello: 'world' });
assert.deepEqual({ hello: 'world', _id: insertedDoc._id, createdAt: insertedDoc.createdAt, updatedAt: insertedDoc.updatedAt }, docs[0]);
done();
});
});
});
});
});
});
it("If timestampData option not set, don't create a createdAt and a updatedAt field", function (done) {
d.insert({ hello: 'world' }, function (err, insertedDoc) {
Object.keys(insertedDoc).length.should.equal(2);
assert.isUndefined(insertedDoc.createdAt);
assert.isUndefined(insertedDoc.updatedAt);
d.find({}, function (err, docs) {
docs.length.should.equal(1);
assert.deepEqual(docs[0], insertedDoc);
done();
});
});
});
it("If timestampData is set but createdAt is specified by user, don't change it", function (done) {
var newDoc = { hello: 'world', createdAt: new Date(234) }, beginning = Date.now();
d = new Datastore({ filename: testDb, timestampData: true, autoload: true });
d.insert(newDoc, function (err, insertedDoc) {
Object.keys(insertedDoc).length.should.equal(4);
insertedDoc.createdAt.getTime().should.equal(234); // Not modified
assert.isBelow(insertedDoc.updatedAt.getTime() - beginning, reloadTimeUpperBound); // Created
d.find({}, function (err, docs) {
assert.deepEqual(insertedDoc, docs[0]);
d.loadDatabase(function () {
d.find({}, function (err, docs) {
assert.deepEqual(insertedDoc, docs[0]);
done();
});
});
});
});
});
it("If timestampData is set but updatedAt is specified by user, don't change it", function (done) {
var newDoc = { hello: 'world', updatedAt: new Date(234) }, beginning = Date.now();
d = new Datastore({ filename: testDb, timestampData: true, autoload: true });
d.insert(newDoc, function (err, insertedDoc) {
Object.keys(insertedDoc).length.should.equal(4);
insertedDoc.updatedAt.getTime().should.equal(234); // Not modified
assert.isBelow(insertedDoc.createdAt.getTime() - beginning, reloadTimeUpperBound); // Created
d.find({}, function (err, docs) {
assert.deepEqual(insertedDoc, docs[0]);
d.loadDatabase(function () {
d.find({}, function (err, docs) {
assert.deepEqual(insertedDoc, docs[0]);
done();
});
});
});
});
});
it('Can insert a doc with id 0', function (done) {
d.insert({ _id: 0, hello: 'world' }, function (err, doc) {
doc._id.should.equal(0);
doc.hello.should.equal('world');
done();
});
});
/**
* Complicated behavior here. Basically we need to test that when a user function throws an exception, it is not caught
* in NeDB and the callback called again, transforming a user error into a NeDB error.
*
* So we need a way to check that the callback is called only once and the exception thrown is indeed the client exception
* Mocha's exception handling mechanism interferes with this since it already registers a listener on uncaughtException
* which we need to use since findOne is not called in the same turn of the event loop (so no try/catch)
* So we remove all current listeners, put our own which when called will register the former listeners (incl. Mocha's) again.
*
* Note: maybe using an in-memory only NeDB would give us an easier solution
*/
it('If the callback throws an uncaught exception, do not catch it inside findOne, this is userspace concern', function (done) {
var tryCount = 0
, currentUncaughtExceptionHandlers = process.listeners('uncaughtException')
, i
;
process.removeAllListeners('uncaughtException');
process.on('uncaughtException', function MINE (ex) {
process.removeAllListeners('uncaughtException');
for (i = 0; i < currentUncaughtExceptionHandlers.length; i += 1) {
process.on('uncaughtException', currentUncaughtExceptionHandlers[i]);
}
ex.message.should.equal('SOME EXCEPTION');
done();
});
d.insert({ a: 5 }, function () {
d.findOne({ a : 5}, function (err, doc) {
if (tryCount === 0) {
tryCount += 1;
throw new Error('SOME EXCEPTION');
} else {
done(new Error('Callback was called twice'));
}
});
});
});
}); // ==== End of 'Insert' ==== //
describe('#getCandidates', function () {
it('Can use an index to get docs with a basic match', function (done) {
d.ensureIndex({ fieldName: 'tf' }, function (err) {
d.insert({ tf: 4 }, function (err, _doc1) {
d.insert({ tf: 6 }, function () {
d.insert({ tf: 4, an: 'other' }, function (err, _doc2) {
d.insert({ tf: 9 }, function () {
d.getCandidates({ r: 6, tf: 4 }, function (err, data) {
var doc1 = _.find(data, function (d) { return d._id === _doc1._id; })
, doc2 = _.find(data, function (d) { return d._id === _doc2._id; })
;
data.length.should.equal(2);
assert.deepEqual(doc1, { _id: doc1._id, tf: 4 });
assert.deepEqual(doc2, { _id: doc2._id, tf: 4, an: 'other' });
done();
});
});
});
});
});
});
});
it('Can use an index to get docs with a $in match', function (done) {
d.ensureIndex({ fieldName: 'tf' }, function (err) {
d.insert({ tf: 4 }, function (err) {
d.insert({ tf: 6 }, function (err, _doc1) {
d.insert({ tf: 4, an: 'other' }, function (err) {
d.insert({ tf: 9 }, function (err, _doc2) {
d.getCandidates({ r: 6, tf: { $in: [6, 9, 5] } }, function (err, data) {
var doc1 = _.find(data, function (d) { return d._id === _doc1._id; })
, doc2 = _.find(data, function (d) { return d._id === _doc2._id; })
;
data.length.should.equal(2);
assert.deepEqual(doc1, { _id: doc1._id, tf: 6 });
assert.deepEqual(doc2, { _id: doc2._id, tf: 9 });
done();
});
});
});
});
});
});
});
it('If no index can be used, return the whole database', function (done) {
d.ensureIndex({ fieldName: 'tf' }, function (err) {
d.insert({ tf: 4 }, function (err, _doc1) {
d.insert({ tf: 6 }, function (err, _doc2) {
d.insert({ tf: 4, an: 'other' }, function (err, _doc3) {
d.insert({ tf: 9 }, function (err, _doc4) {
d.getCandidates({ r: 6, notf: { $in: [6, 9, 5] } }, function (err, data) {
var doc1 = _.find(data, function (d) { return d._id === _doc1._id; })
, doc2 = _.find(data, function (d) { return d._id === _doc2._id; })
, doc3 = _.find(data, function (d) { return d._id === _doc3._id; })
, doc4 = _.find(data, function (d) { return d._id === _doc4._id; })
;
data.length.should.equal(4);
assert.deepEqual(doc1, { _id: doc1._id, tf: 4 });
assert.deepEqual(doc2, { _id: doc2._id, tf: 6 });
assert.deepEqual(doc3, { _id: doc3._id, tf: 4, an: 'other' });
assert.deepEqual(doc4, { _id: doc4._id, tf: 9 });
done();
});
});
});
});
});
});
});
it('Can use indexes for comparison matches', function (done) {
d.ensureIndex({ fieldName: 'tf' }, function (err) {
d.insert({ tf: 4 }, function (err, _doc1) {
d.insert({ tf: 6 }, function (err, _doc2) {
d.insert({ tf: 4, an: 'other' }, function (err, _doc3) {
d.insert({ tf: 9 }, function (err, _doc4) {
d.getCandidates({ r: 6, tf: { $lte: 9, $gte: 6 } }, function (err, data) {
var doc2 = _.find(data, function (d) { return d._id === _doc2._id; })
, doc4 = _.find(data, function (d) { return d._id === _doc4._id; })
;
data.length.should.equal(2);
assert.deepEqual(doc2, { _id: doc2._id, tf: 6 });
assert.deepEqual(doc4, { _id: doc4._id, tf: 9 });
done();
});
});
});
});
});
});
});
it("Can set a TTL index that expires documents", function (done) {
d.ensureIndex({ fieldName: 'exp', expireAfterSeconds: 0.2 }, function () {
d.insert({ hello: 'world', exp: new Date() }, function () {
setTimeout(function () {
d.findOne({}, function (err, doc) {
assert.isNull(err);
doc.hello.should.equal('world');
setTimeout(function () {
d.findOne({}, function (err, doc) {
assert.isNull(err);
assert.isNull(doc);
d.on('compaction.done', function () {
// After compaction, no more mention of the document, correctly removed
var datafileContents = fs.readFileSync(testDb, 'utf8');
datafileContents.split('\n').length.should.equal(2);
assert.isNull(datafileContents.match(/world/));
// New datastore on same datafile is empty
var d2 = new Datastore({ filename: testDb, autoload: true });
d2.findOne({}, function (err, doc) {
assert.isNull(err);
assert.isNull(doc);
done();
});
});
d.persistence.compactDatafile();
});
}, 101);
});
}, 100);
});
});
});
it("TTL indexes can expire multiple documents and only what needs to be expired", function (done) {
d.ensureIndex({ fieldName: 'exp', expireAfterSeconds: 0.2 }, function () {
d.insert({ hello: 'world1', exp: new Date() }, function () {
d.insert({ hello: 'world2', exp: new Date() }, function () {
d.insert({ hello: 'world3', exp: new Date((new Date()).getTime() + 100) }, function () {
setTimeout(function () {
d.find({}, function (err, docs) {
assert.isNull(err);
docs.length.should.equal(3);
setTimeout(function () {
d.find({}, function (err, docs) {
assert.isNull(err);
docs.length.should.equal(1);
docs[0].hello.should.equal('world3');
setTimeout(function () {
d.find({}, function (err, docs) {
assert.isNull(err);
docs.length.should.equal(0);
done();
});
}, 101);
});
}, 101);
});
}, 100);
});
});
});
});
});
it("Document where indexed field is absent or not a date are ignored", function (done) {
d.ensureIndex({ fieldName: 'exp', expireAfterSeconds: 0.2 }, function () {
d.insert({ hello: 'world1', exp: new Date() }, function () {
d.insert({ hello: 'world2', exp: "not a date" }, function () {
d.insert({ hello: 'world3' }, function () {
setTimeout(function () {
d.find({}, function (err, docs) {
assert.isNull(err);
docs.length.should.equal(3);
setTimeout(function () {
d.find({}, function (err, docs) {
assert.isNull(err);
docs.length.should.equal(2);
docs[0].hello.should.not.equal('world1');
docs[1].hello.should.not.equal('world1');
done();
});
}, 101);
});
}, 100);
});
});
});
});
});
}); // ==== End of '#getCandidates' ==== //
describe('Find', function () {
it('Can find all documents if an empty query is used', function (done) {
async.waterfall([
function (cb) {
d.insert({ somedata: 'ok' }, function (err) {
d.insert({ somedata: 'another', plus: 'additional data' }, function (err) {
d.insert({ somedata: 'again' }, function (err) { return cb(err); });
});
});
}
, function (cb) { // Test with empty object
d.find({}, function (err, docs) {
assert.isNull(err);
docs.length.should.equal(3);
_.pluck(docs, 'somedata').should.contain('ok');
_.pluck(docs, 'somedata').should.contain('another');
_.find(docs, function (d) { return d.somedata === 'another' }).plus.should.equal('additional data');
_.pluck(docs, 'somedata').should.contain('again');
return cb();
});
}
], done);
});
it('Can find all documents matching a basic query', function (done) {
async.waterfall([
function (cb) {
d.insert({ somedata: 'ok' }, function (err) {
d.insert({ somedata: 'again', plus: 'additional data' }, function (err) {
d.insert({ somedata: 'again' }, function (err) { return cb(err); });
});
});
}
, function (cb) { // Test with query that will return docs
d.find({ somedata: 'again' }, function (err, docs) {
assert.isNull(err);
docs.length.should.equal(2);
_.pluck(docs, 'somedata').should.not.contain('ok');
return cb();
});
}
, function (cb) { // Test with query that doesn't match anything
d.find({ somedata: 'nope' }, function (err, docs) {
assert.isNull(err);
docs.length.should.equal(0);
return cb();
});
}
], done);
});
it('Can find one document matching a basic query and return null if none is found', function (done) {
async.waterfall([
function (cb) {
d.insert({ somedata: 'ok' }, function (err) {
d.insert({ somedata: 'again', plus: 'additional data' }, function (err) {
d.insert({ somedata: 'again' }, function (err) { return cb(err); });
});
});
}
, function (cb) { // Test with query that will return docs
d.findOne({ somedata: 'ok' }, function (err, doc) {
assert.isNull(err);
Object.keys(doc).length.should.equal(2);
doc.somedata.should.equal('ok');
assert.isDefined(doc._id);
return cb();
});
}
, function (cb) { // Test with query that doesn't match anything
d.findOne({ somedata: 'nope' }, function (err, doc) {
assert.isNull(err);
assert.isNull(doc);
return cb();
});
}
], done);
});
it('Can find dates and objects (non JS-native types)', function (done) {
var date1 = new Date(1234543)
, date2 = new Date(9999)
;
d.insert({ now: date1, sth: { name: 'nedb' } }, function () {
d.findOne({ now: date1 }, function (err, doc) {
assert.isNull(err);
doc.sth.name.should.equal('nedb');
d.findOne({ now: date2 }, function (err, doc) {
assert.isNull(err);
assert.isNull(doc);
d.findOne({ sth: { name: 'nedb' } }, function (err, doc) {
assert.isNull(err);
doc.sth.name.should.equal('nedb');
d.findOne({ sth: { name: 'other' } }, function (err, doc) {
assert.isNull(err);
assert.isNull(doc);
done();
});
});
});
});
});
});
it('Can use dot-notation to query subfields', function (done) {
d.insert({ greeting: { english: 'hello' } }, function () {
d.findOne({ "greeting.english": 'hello' }, function (err, doc) {
assert.isNull(err);
doc.greeting.english.should.equal('hello');
d.findOne({ "greeting.english": 'hellooo' }, function (err, doc) {
assert.isNull(err);
assert.isNull(doc);
d.findOne({ "greeting.englis": 'hello' }, function (err, doc) {
assert.isNull(err);
assert.isNull(doc);
done();
});
});
});
});
});
it('Array fields match if any element matches', function (done) {
d.insert({ fruits: ['pear', 'apple', 'banana'] }, function (err, doc1) {
d.insert({ fruits: ['coconut', 'orange', 'pear'] }, function (err, doc2) {
d.insert({ fruits: ['banana'] }, function (err, doc3) {
d.find({ fruits: 'pear' }, function (err, docs) {
assert.isNull(err);
docs.length.should.equal(2);
_.pluck(docs, '_id').should.contain(doc1._id);
_.pluck(docs, '_id').should.contain(doc2._id);
d.find({ fruits: 'banana' }, function (err, docs) {
assert.isNull(err);
docs.length.should.equal(2);
_.pluck(docs, '_id').should.contain(doc1._id);
_.pluck(docs, '_id').should.contain(doc3._id);
d.find({ fruits: 'doesntexist' }, function (err, docs) {
assert.isNull(err);
docs.length.should.equal(0);
done();
});
});
});
});
});
});
});
it('Returns an error if the query is not well formed', function (done) {
d.insert({ hello: 'world' }, function () {
d.find({ $or: { hello: 'world' } }, function (err, docs) {
assert.isDefined(err);
assert.isUndefined(docs);
d.findOne({ $or: { hello: 'world' } }, function (err, doc) {
assert.isDefined(err);
assert.isUndefined(doc);
done();
});
});
});
});
it('Changing the documents returned by find or findOne do not change the database state', function (done) {
d.insert({ a: 2, hello: 'world' }, function () {
d.findOne({ a: 2 }, function (err, doc) {
doc.hello = 'changed';
d.findOne({ a: 2 }, function (err, doc) {
doc.hello.should.equal('world');
d.find({ a: 2 }, function (err, docs) {
docs[0].hello = 'changed';
d.findOne({ a: 2 }, function (err, doc) {
doc.hello.should.equal('world');
done();
});
});
});
});
});
});
it('Can use sort, skip and limit if the callback is not passed to find but to exec', function (done) {
d.insert({ a: 2, hello: 'world' }, function () {
d.insert({ a: 24, hello: 'earth' }, function () {
d.insert({ a: 13, hello: 'blueplanet' }, function () {
d.insert({ a: 15, hello: 'home' }, function () {
d.find({}).sort({ a: 1 }).limit(2).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(2);
docs[0].hello.should.equal('world');
docs[1].hello.should.equal('blueplanet');
done();
});
});
});
});
});
});
it('Can use sort and skip if the callback is not passed to findOne but to exec', function (done) {
d.insert({ a: 2, hello: 'world' }, function () {
d.insert({ a: 24, hello: 'earth' }, function () {
d.insert({ a: 13, hello: 'blueplanet' }, function () {
d.insert({ a: 15, hello: 'home' }, function () {
// No skip no query
d.findOne({}).sort({ a: 1 }).exec(function (err, doc) {
assert.isNull(err);
doc.hello.should.equal('world');
// A query
d.findOne({ a: { $gt: 14 } }).sort({ a: 1 }).exec(function (err, doc) {
assert.isNull(err);
doc.hello.should.equal('home');
// And a skip
d.findOne({ a: { $gt: 14 } }).sort({ a: 1 }).skip(1).exec(function (err, doc) {
assert.isNull(err);
doc.hello.should.equal('earth');
// No result
d.findOne({ a: { $gt: 14 } }).sort({ a: 1 }).skip(2).exec(function (err, doc) {
assert.isNull(err);
assert.isNull(doc);
done();
});
});
});
});
});
});
});
});
});
it('Can use projections in find, normal or cursor way', function (done) {
d.insert({ a: 2, hello: 'world' }, function (err, doc0) {
d.insert({ a: 24, hello: 'earth' }, function (err, doc1) {
d.find({ a: 2 }, { a: 0, _id: 0 }, function (err, docs) {
assert.isNull(err);
docs.length.should.equal(1);
assert.deepEqual(docs[0], { hello: 'world' });
d.find({ a: 2 }, { a: 0, _id: 0 }).exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(1);
assert.deepEqual(docs[0], { hello: 'world' });
// Can't use both modes at once if not _id
d.find({ a: 2 }, { a: 0, hello: 1 }, function (err, docs) {
assert.isNotNull(err);
assert.isUndefined(docs);
d.find({ a: 2 }, { a: 0, hello: 1 }).exec(function (err, docs) {
assert.isNotNull(err);
assert.isUndefined(docs);
done();
});
});
});
});
});
});
});
it('Can use projections in findOne, normal or cursor way', function (done) {
d.insert({ a: 2, hello: 'world' }, function (err, doc0) {
d.insert({ a: 24, hello: 'earth' }, function (err, doc1) {
d.findOne({ a: 2 }, { a: 0, _id: 0 }, function (err, doc) {
assert.isNull(err);
assert.deepEqual(doc, { hello: 'world' });
d.findOne({ a: 2 }, { a: 0, _id: 0 }).exec(function (err, doc) {
assert.isNull(err);
assert.deepEqual(doc, { hello: 'world' });
// Can't use both modes at once if not _id
d.findOne({ a: 2 }, { a: 0, hello: 1 }, function (err, doc) {
assert.isNotNull(err);
assert.isUndefined(doc);
d.findOne({ a: 2 }, { a: 0, hello: 1 }).exec(function (err, doc) {
assert.isNotNull(err);
assert.isUndefined(doc);
done();
});
});
});
});
});
});
});
}); // ==== End of 'Find' ==== //
describe('Count', function() {
it('Count all documents if an empty query is used', function (done) {
async.waterfall([
function (cb) {
d.insert({ somedata: 'ok' }, function (err) {
d.insert({ somedata: 'another', plus: 'additional data' }, function (err) {
d.insert({ somedata: 'again' }, function (err) { return cb(err); });
});
});
}
, function (cb) { // Test with empty object
d.count({}, function (err, docs) {
assert.isNull(err);
docs.should.equal(3);
return cb();
});
}
], done);
});
it('Count all documents matching a basic query', function (done) {
async.waterfall([
function (cb) {
d.insert({ somedata: 'ok' }, function (err) {
d.insert({ somedata: 'again', plus: 'additional data' }, function (err) {
d.insert({ somedata: 'again' }, function (err) { return cb(err); });
});
});
}
, function (cb) { // Test with query that will return docs
d.count({ somedata: 'again' }, function (err, docs) {
assert.isNull(err);
docs.should.equal(2);
return cb();
});
}
, function (cb) { // Test with query that doesn't match anything
d.count({ somedata: 'nope' }, function (err, docs) {
assert.isNull(err);
docs.should.equal(0);
return cb();
});
}
], done);
});
it('Array fields match if any element matches', function (done) {
d.insert({ fruits: ['pear', 'apple', 'banana'] }, function (err, doc1) {
d.insert({ fruits: ['coconut', 'orange', 'pear'] }, function (err, doc2) {
d.insert({ fruits: ['banana'] }, function (err, doc3) {
d.count({ fruits: 'pear' }, function (err, docs) {
assert.isNull(err);