deno.land / x / mongoose@6.7.5 / test / timestamps.test.js

timestamps.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
'use strict';
const start = require('./common');
const assert = require('assert');
const mongoose = start.mongoose;const Schema = mongoose.Schema;
describe('timestamps', function() { let db;
before(function() { db = start(); });
after(async function() { await db.close(); });
beforeEach(() => db.deleteModel(/.*/)); afterEach(() => require('./util').clearTestData(db)); afterEach(() => require('./util').stopRemainingOps(db));
// These tests use schemas only, no database connection needed. describe('schema options', function() { it('should have createdAt and updatedAt fields', function(done) { const TestSchema = new Schema({ name: String }, { timestamps: true });
assert.ok(TestSchema.path('createdAt')); assert.ok(TestSchema.path('updatedAt')); done(); });
it('should have createdAt and updatedAt fields', function(done) { const TestSchema = new Schema({ name: String });
TestSchema.set('timestamps', true);
assert.ok(TestSchema.path('createdAt')); assert.ok(TestSchema.path('updatedAt')); done(); });
it('should have created and updatedAt fields', function(done) { const TestSchema = new Schema({ name: String }, { timestamps: { createdAt: 'created' } });
assert.ok(TestSchema.path('created')); assert.ok(TestSchema.path('updatedAt')); done(); });
it('should have created and updatedAt fields', function(done) { const TestSchema = new Schema({ name: String });
TestSchema.set('timestamps', { createdAt: 'created' });
assert.ok(TestSchema.path('created')); assert.ok(TestSchema.path('updatedAt')); done(); });
it('should have created and updated fields', function(done) { const TestSchema = new Schema({ name: String }, { timestamps: { createdAt: 'created', updatedAt: 'updated' } });
assert.ok(TestSchema.path('created')); assert.ok(TestSchema.path('updated')); done(); });
it('should have just createdAt if updatedAt set to falsy', function(done) { const TestSchema = new Schema({ name: String });
TestSchema.set('timestamps', { updatedAt: false });
assert.ok(TestSchema.path('createdAt')); assert.ok(!TestSchema.path('updatedAt')); done(); });
it('should have created and updated fields', function(done) { const TestSchema = new Schema({ name: String });
TestSchema.set('timestamps', { createdAt: 'created', updatedAt: 'updated' });
assert.ok(TestSchema.path('created')); assert.ok(TestSchema.path('updated')); done(); });
it('TTL index with timestamps (gh-5656)', function() { const testSchema = new Schema({ foo: String, updatedAt: { type: Date, expires: '2h' } }, { timestamps: true });
const indexes = testSchema.indexes(); assert.deepEqual(indexes, [ [{ updatedAt: 1 }, { background: true, expireAfterSeconds: 7200 }] ]); }); });
it('does not override timestamp params defined in schema (gh-4868)', function(done) { const startTime = Date.now(); const schema = new mongoose.Schema({ createdAt: { type: Date, select: false }, updatedAt: { type: Date, select: true }, name: String }, { timestamps: true }); const M = db.model('Test', schema);
M.create({ name: 'Test' }, function(error, doc) { assert.ifError(error); M.findOne({ _id: doc._id }, function(error, doc) { assert.ifError(error); assert.ok(!doc.createdAt); assert.ok(doc.updatedAt); assert.ok(doc.updatedAt.valueOf() >= startTime); done(); }); }); });
it('updatedAt without createdAt (gh-5598)', function(done) { const startTime = Date.now(); const schema = new mongoose.Schema({ name: String }, { timestamps: { createdAt: null, updatedAt: true } }); const M = db.model('Test', schema);
M.create({ name: 'Test' }, function(error, doc) { assert.ifError(error); M.findOne({ _id: doc._id }, function(error, doc) { assert.ifError(error); assert.ok(!doc.createdAt); assert.ok(doc.updatedAt); assert.ok(doc.updatedAt.valueOf() >= startTime); done(); }); }); });
it('updatedAt without createdAt for nested (gh-5598)', function(done) { const startTime = Date.now(); const schema = new mongoose.Schema({ name: String }, { timestamps: { createdAt: null, updatedAt: true } }); const parentSchema = new mongoose.Schema({ child: schema }); const M = db.model('Test', parentSchema);
M.create({ child: { name: 'test' } }, function(error, doc) { assert.ifError(error); M.findOne({ _id: doc._id }, function(error, doc) { assert.ifError(error); assert.ok(!doc.child.createdAt); assert.ok(doc.child.updatedAt); assert.ok(doc.child.updatedAt.valueOf() >= startTime); done(); }); }); });
it('nested paths (gh-4503)', function(done) { const startTime = Date.now(); const schema = new mongoose.Schema({ name: String }, { timestamps: { createdAt: 'ts.c', updatedAt: 'ts.a' } }); const M = db.model('Test', schema);
M.create({ name: 'Test' }, function(error, doc) { assert.ifError(error); M.findOne({ _id: doc._id }, function(error, doc) { assert.ifError(error); assert.ok(doc.ts.c); assert.ok(doc.ts.c.valueOf() >= startTime); assert.ok(doc.ts.a); assert.ok(doc.ts.a.valueOf() >= startTime); done(); }); }); });
it('does not override nested timestamp params defined in schema (gh-4868)', function(done) { const startTime = Date.now(); const schema = new mongoose.Schema({ ts: { createdAt: { type: Date, select: false }, updatedAt: { type: Date, select: true } }, name: String }, { timestamps: { createdAt: 'ts.createdAt', updatedAt: 'ts.updatedAt' } }); const M = db.model('Test', schema);
M.create({ name: 'Test' }, function(error, doc) { assert.ifError(error); M.findOne({ _id: doc._id }, function(error, doc) { assert.ifError(error); assert.ok(!doc.ts.createdAt); assert.ok(doc.ts.updatedAt); assert.ok(doc.ts.updatedAt.valueOf() >= startTime); done(); }); }); });
it('does not override timestamps in nested schema (gh-4868)', function(done) { const startTime = Date.now(); const tsSchema = new mongoose.Schema({ createdAt: { type: Date, select: false }, updatedAt: { type: Date, select: true } }); const schema = new mongoose.Schema({ ts: tsSchema, name: String }, { timestamps: { createdAt: 'ts.createdAt', updatedAt: 'ts.updatedAt' } }); const M = db.model('Test', schema);
M.create({ name: 'Test' }, function(error, doc) { assert.ifError(error); M.findOne({ _id: doc._id }, function(error, doc) { assert.ifError(error); assert.ok(!doc.ts.createdAt); assert.ok(doc.ts.updatedAt); assert.ok(doc.ts.updatedAt.valueOf() >= startTime); done(); }); }); });
it('no timestamps added when parent/child timestamps explicitly false (gh-7202)', function(done) { const subSchema = new Schema({}, { timestamps: false }); const schema = new Schema({ sub: subSchema }, { timestamps: false });
const Test = db.model('Test', schema); const test = new Test({ sub: {} });
test.save((err, saved) => { assert.ifError(err); assert.strictEqual(saved.createdAt, undefined); assert.strictEqual(saved.updatedAt, undefined); assert.strictEqual(saved.sub.createdAt, undefined); assert.strictEqual(saved.sub.updatedAt, undefined); done(); }); });
it('avoids calling createdAt getters when setting updatedAt (gh-7496)', function() { const modelSchema = new Schema({ createdAt: { type: Date, get: (date) => date && date.valueOf() / 1000 }, updatedAt: { type: Date, get: (date) => date && date.valueOf() / 1000 } }, { timestamps: true });
const Model = db.model('Test', modelSchema);
const start = new Date(); return Model.create({}).then(doc => { assert.ok(doc._doc.createdAt.valueOf() >= start.valueOf()); assert.ok(doc._doc.updatedAt.valueOf() >= start.valueOf()); }); });
it('handles custom statics that conflict with built-in functions (gh-7698)', function() { const schema = new mongoose.Schema({ name: String }, { timestamps: true });
let called = 0; schema.statics.updateOne = function() { ++called; return mongoose.Model.updateOne.apply(this, arguments); }; const M = db.model('Test', schema);
const startTime = Date.now(); return M.deleteMany({}). then(() => M.updateOne({}, { name: 'foo' }, { upsert: true })). then(() => assert.equal(called, 1)). then(() => M.findOne()). then(doc => assert.ok(doc.createdAt.valueOf() >= startTime)); });
it('timestamps handle reusing child schemas (gh-7712)', async function() { const childSchema = new mongoose.Schema({ name: String }, { timestamps: true }); const M1 = db.model('Test', new mongoose.Schema({ child: childSchema })); const M2 = db.model('Test1', new mongoose.Schema({ children: [childSchema] }));
let startTime = null; let doc = await M1.create({ child: { name: 'foo' } }); assert.ok(doc.child.updatedAt); await new Promise(resolve => setTimeout(resolve, 25)); startTime = Date.now();
doc = await M1.findOneAndUpdate({}, { $set: { 'child.name': 'bar' } }, { new: true }); assert.ok(doc.child.updatedAt.valueOf() >= startTime, `Timestamp not updated: ${doc.child.updatedAt}`);
doc = await M2.create({ children: [{ name: 'foo' }] }); assert.ok(doc.children[0].updatedAt); await new Promise(resolve => setTimeout(resolve, 25)); startTime = Date.now();
doc = await M2.findOneAndUpdate({ 'children.name': 'foo' }, { $set: { 'children.$.name': 'bar' } }, { new: true }); assert.ok(doc.children[0].updatedAt.valueOf() >= startTime, `Timestamp not updated: ${doc.children[0].updatedAt}`); });
it('respects timestamps: false in child schema (gh-8007)', async function() { const sub = Schema({ name: String }, { timestamps: false, _id: false }); const schema = Schema({ data: sub });
const Model = db.model('Test', schema);
let res = await Model.create({ data: {} });
await Model.bulkWrite([ { updateOne: { filter: { _id: res._id }, update: { 'data.name': 'foo' } } } ]);
res = await Model.findOne({}).lean(); assert.deepEqual(res.data, { name: 'foo' }); });
it('updates updatedAt when calling update without $set (gh-4768)', async function() { const Model = db.model('Test', Schema({ name: String }, { timestamps: true }));
let doc = await Model.create({ name: 'test1' }); const start = doc.updatedAt;
await delay(50); doc = await Model.findOneAndUpdate({}, doc.toObject(), { new: true }); assert.ok(doc.updatedAt > start, `${doc.updatedAt} >= ${start}`); });
it('updates updatedAt when calling update on subchild', async function() { const subchildschema = new mongoose.Schema({ name: String }, { timestamps: true }); const schema = new mongoose.Schema({ name: String, subchild: subchildschema }, { timestamps: true }); const parentSchema = new mongoose.Schema({ child: schema }, { timestamps: true });
const Model = db.model('Test', parentSchema);
let doc = await Model.create({ name: 'test', child: { name: 'child', subchild: { name: 'subchild' } } }); assert.ok(doc.child.updatedAt); const startTime = doc.createdAt; await new Promise(resolve => setTimeout(resolve), 25);
doc = await Model.findOneAndUpdate({}, { $set: { 'child.subchild.name': 'subChildUpdated' } }, { new: true });
assert.ok(doc.updatedAt.valueOf() > startTime, `Parent Timestamp not updated: ${doc.updatedAt}`); assert.ok(doc.child.updatedAt.valueOf() > startTime, `Child Timestamp not updated: ${doc.updatedAt}`); assert.ok(doc.child.subchild.updatedAt.valueOf() > startTime, `SubChild Timestamp not updated: ${doc.updatedAt}`); });
it('sets timestamps on deeply nested docs on upsert (gh-8894)', function() { const JournalSchema = Schema({ message: String }, { timestamps: true }); const ProductSchema = Schema({ name: String, journal: [JournalSchema], lastJournal: JournalSchema }, { timestamps: true }); const schema = Schema({ products: [ProductSchema] }, { timestamps: true }); const Order = db.model('Order', schema);
const update = { products: [{ name: 'ASUS Vivobook Pro', journal: [{ message: 'out of stock' }], lastJournal: { message: 'out of stock' } }] };
return Order.findOneAndUpdate({}, update, { upsert: true, new: true }). then(doc => { assert.ok(doc.products[0].journal[0].createdAt); assert.ok(doc.products[0].journal[0].updatedAt);
assert.ok(doc.products[0].lastJournal.createdAt); assert.ok(doc.products[0].lastJournal.updatedAt); }); });
it('sets timestamps on bulk write without `$set` (gh-9268)', async function() { const NestedSchema = new Schema({ name: String }, { timestamps: true, _id: false }); const TestSchema = new Schema({ nestedDoc: NestedSchema }); const Test = db.model('Test', TestSchema);
await Test.create({ nestedDoc: { name: 'test' } }); const doc = await Test.findOne().lean();
await delay(10); await Test.bulkWrite([ { updateOne: { filter: {}, update: { 'nestedDoc.name': 'test2' } } } ]);
const newDoc = await Test.findById(doc).lean(); assert.ok(newDoc.nestedDoc.updatedAt > doc.nestedDoc.updatedAt); });
it('works with property named "set" (gh-9428)', function() { const schema = new Schema({ set: String }, { timestamps: true }); const Model = db.model('Test', schema);
return Model.create({ set: 'test' }).then(doc => assert.ok(doc.createdAt)); });
it('should not override createdAt when not selected (gh-4340)', function(done) { const TestSchema = new Schema({ name: String }, { timestamps: true });
const Test = db.model('Test', TestSchema);
Test.create({ name: 'hello' }, function(err, doc) { // Let’s save the dates to compare later. const createdAt = doc.createdAt; const updatedAt = doc.updatedAt;
assert.ok(doc.createdAt);
Test.findById(doc._id, { name: true }, function(err, doc) { // The dates shouldn’t be selected here. assert.ok(!doc.createdAt); assert.ok(!doc.updatedAt);
doc.name = 'world';
doc.save(function(err, doc) { // Let’s save the new updatedAt date as it should have changed. const newUpdatedAt = doc.updatedAt;
assert.ok(!doc.createdAt); assert.ok(doc.updatedAt);
Test.findById(doc._id, function(err, doc) { // Let’s make sure that everything is working again by // comparing the dates with the ones we saved. assert.equal(doc.createdAt.valueOf(), createdAt.valueOf()); assert.notEqual(doc.updatedAt.valueOf(), updatedAt.valueOf()); assert.equal(doc.updatedAt.valueOf(), newUpdatedAt.valueOf());
done(); }); }); }); }); });
describe('auto update createdAt and updatedAt when create/save/update document', function() { let CatSchema; let Cat;
beforeEach(function() { CatSchema = new Schema({ name: String, hobby: String }, { timestamps: true }); Cat = db.model('Cat', CatSchema); return Cat.deleteMany({}).then(() => Cat.create({ name: 'newcat' })); });
it('should have fields when create', function(done) { const cat = new Cat({ name: 'newcat' }); cat.save(function(err, doc) { assert.ok(doc.createdAt); assert.ok(doc.updatedAt); assert.ok(doc.createdAt.getTime() === doc.updatedAt.getTime()); done(); }); });
it('sets timestamps on findOneAndUpdate', function(done) { Cat.findOneAndUpdate({ name: 'notexistname' }, { $set: {} }, { upsert: true, new: true }, function(err, doc) { assert.ok(doc.createdAt); assert.ok(doc.updatedAt); assert.ok(doc.createdAt.getTime() === doc.updatedAt.getTime()); done(); }); });
it('sets timestamps on findOneAndReplace (gh-9951)', function() { return Cat.findOneAndReplace({ name: 'notexistname' }, {}, { upsert: true, new: true }).then(doc => { assert.ok(doc.createdAt); assert.ok(doc.updatedAt); assert.ok(doc.createdAt.getTime() === doc.updatedAt.getTime()); }); });
it('should change updatedAt when save', function(done) { Cat.findOne({ name: 'newcat' }, function(err, doc) { const old = doc.updatedAt;
doc.hobby = 'coding';
doc.save(function(err, doc) { assert.ok(doc.updatedAt.getTime() > old.getTime()); done(); }); }); });
it('should not change updatedAt when save with no modifications', function(done) { Cat.findOne({ name: 'newcat' }, function(err, doc) { const old = doc.updatedAt;
doc.save(function(err, doc) { assert.ok(doc.updatedAt.getTime() === old.getTime()); done(); }); }); });
it('can skip with timestamps: false (gh-7357)', async function() { const cat = await Cat.findOne();
const old = cat.updatedAt;
await delay(10);
cat.hobby = 'fishing';
await cat.save({ timestamps: false });
assert.strictEqual(cat.updatedAt, old); });
it('can skip with `$timestamps(false)` (gh-12117)', async function() { const cat = await Cat.findOne(); const old = cat.updatedAt;
await delay(10);
cat.hobby = 'fishing';
cat.$timestamps(false); await cat.save();
assert.strictEqual(cat.updatedAt, old); });
it('should change updatedAt when findOneAndUpdate', function(done) { Cat.create({ name: 'test123' }, function(err) { assert.ifError(err); Cat.findOne({ name: 'test123' }, function(err, doc) { const old = doc.updatedAt; Cat.findOneAndUpdate({ name: 'test123' }, { $set: { hobby: 'fish' } }, { new: true }, function(err, doc) { assert.ok(doc.updatedAt.getTime() > old.getTime()); done(); }); }); }); });
it('insertMany with createdAt off (gh-6381)', async function() { const CatSchema = new Schema({ name: String, createdAt: { type: Date, default: function() { return new Date('2013-06-01'); } } }, { timestamps: { createdAt: false, updatedAt: true } });
const Cat = db.model('Test', CatSchema);
const d = new Date('2011-06-01');
await Cat.deleteMany({}); await Cat.insertMany([{ name: 'a' }, { name: 'b', createdAt: d }]);
const cats = await Cat.find().sort('name');
assert.equal(cats[0].createdAt.valueOf(), new Date('2013-06-01').valueOf()); assert.equal(cats[1].createdAt.valueOf(), new Date('2011-06-01').valueOf()); });
it('should have fields when update', function(done) { Cat.findOne({ name: 'newcat' }, function(err, doc) { const old = doc.updatedAt; Cat.update({ name: 'newcat' }, { $set: { hobby: 'fish' } }, function() { Cat.findOne({ name: 'newcat' }, function(err, doc) { assert.ok(doc.updatedAt.getTime() > old.getTime()); done(); }); }); }); });
it('should change updatedAt when updateOne', function(done) { Cat.findOne({ name: 'newcat' }, function(err, doc) { const old = doc.updatedAt; Cat.updateOne({ name: 'newcat' }, { $set: { hobby: 'fish' } }, function() { Cat.findOne({ name: 'newcat' }, function(err, doc) { assert.ok(doc.updatedAt.getTime() > old.getTime()); done(); }); }); }); });
it('should change updatedAt when updateMany', function(done) { Cat.findOne({ name: 'newcat' }, function(err, doc) { const old = doc.updatedAt; Cat.updateMany({ name: 'newcat' }, { $set: { hobby: 'fish' } }, function() { Cat.findOne({ name: 'newcat' }, function(err, doc) { assert.ok(doc.updatedAt.getTime() > old.getTime()); done(); }); }); }); });
it('nested docs (gh-4049)', function(done) { const GroupSchema = new Schema({ cats: [CatSchema] });
const Group = db.model('Test', GroupSchema); const now = Date.now(); Group.create({ cats: [{ name: 'Garfield' }] }, function(error, group) { assert.ifError(error); assert.ok(group.cats[0].createdAt); assert.ok(group.cats[0].createdAt.getTime() >= now); done(); }); });
it('nested docs with push (gh-4049)', function(done) { const GroupSchema = new Schema({ cats: [CatSchema] });
const Group = db.model('Test', GroupSchema); const now = Date.now(); Group.create({ cats: [{ name: 'Garfield' }] }, function(error, group) { assert.ifError(error); group.cats.push({ name: 'Keanu' }); group.save(function(error) { assert.ifError(error); Group.findById(group._id, function(error, group) { assert.ifError(error); assert.ok(group.cats[1].createdAt); assert.ok(group.cats[1].createdAt.getTime() > now); done(); }); }); }); }); });
it('timestamps with number types (gh-3957)', async function() { const schema = Schema({ createdAt: Number, updatedAt: Number, name: String }, { timestamps: true }); const Model = db.model('Test', schema); const start = Date.now();
const doc = await Model.create({ name: 'test' });
assert.equal(typeof doc.createdAt, 'number'); assert.equal(typeof doc.updatedAt, 'number'); assert.ok(doc.createdAt >= start); assert.ok(doc.updatedAt >= start); });
it('timestamps with custom timestamp (gh-3957)', async function() { const schema = Schema({ createdAt: Number, updatedAt: Number, name: String }, { timestamps: { currentTime: () => 42 } }); const Model = db.model('Test', schema);
const doc = await Model.create({ name: 'test' });
assert.equal(typeof doc.createdAt, 'number'); assert.equal(typeof doc.updatedAt, 'number'); assert.equal(doc.createdAt, 42); assert.equal(doc.updatedAt, 42); });
it('timestamps with custom timestamp using getter method (gh-3957)', async function() { const now = Date.now(); const schema = Schema({ createdAt: { type: Schema.Types.Number, get: (createdAt) => new Date(createdAt * 1000) }, updatedAt: { type: Schema.Types.Number, get: (updatedAt) => new Date(updatedAt * 1000) }, name: String }, { timestamps: { currentTime: () => Math.floor(now / 1000) } }); const Model = db.model('Test', schema); const doc = await Model.create({ name: 'test' });
assert.equal(typeof doc.createdAt, 'object'); assert.equal(typeof doc.updatedAt, 'object'); assert.equal(Math.floor(doc.createdAt.getTime() / 1000), Math.floor(now / 1000)); assert.equal(Math.floor(doc.updatedAt.getTime() / 1000), Math.floor(now / 1000)); });
it('shouldnt bump updatedAt in single nested subdocs that are not modified (gh-9357)', async function() { const nestedSchema = Schema({ nestedA: { type: String }, nestedB: { type: String } }, { timestamps: true }); const parentSchema = Schema({ content: { a: nestedSchema, b: nestedSchema, c: String } });
const Parent = db.model('Test', parentSchema);
await Parent.deleteMany({});
const _id = await Parent.create({ content: { a: { nestedA: 'a' }, b: { nestedB: 'b' } } }).then(doc => doc._id);
const doc = await Parent.findById(_id);
const ts = doc.content.b.updatedAt; doc.content.a.nestedA = 'b'; await delay(10); await doc.save();
const fromDb = await Parent.findById(_id); assert.strictEqual(fromDb.content.b.updatedAt.valueOf(), ts.valueOf()); });
it('bumps updatedAt with mixed $set (gh-9357)', async function() { const nestedSchema = Schema({ nestedA: { type: String }, nestedB: { type: String } }, { timestamps: true }); const parentSchema = Schema({ content: { a: nestedSchema, b: nestedSchema, c: String } });
const Parent = db.model('Test', parentSchema);
await Parent.deleteMany({});
const doc = await Parent.create({ content: { a: { nestedA: 'a' }, b: { nestedB: 'b' } } }); const ts = doc.content.b.updatedAt;
await delay(10); const fromDb = await Parent.findOneAndUpdate({}, { 'content.c': 'value', $set: { 'content.a.nestedA': 'value' } }, { new: true });
assert.ok(fromDb.content.a.updatedAt.valueOf() > ts.valueOf()); });
it('makes createdAt immutable by default (gh-10139)', async function() { const schema = Schema({ name: String }, { timestamps: true }); const Model = db.model('Time', schema); const doc = await Model.create({ name: 'test' }); const test = doc.createdAt; doc.createdAt = new Date(); assert.equal(test, doc.createdAt); });
it('sets createdAt when using $push/$addToSet on path with positional operator (gh-10447)', async function() { const userSchema = new Schema({ email: String }, { timestamps: true }); const eventSchema = new Schema({ users: [userSchema], message: String }, { timestamps: true });
const churchSchema = new Schema({ events: [eventSchema] }, { timestamps: true });
const Church = db.model('Test', churchSchema);
await Church.create({ events: [{ churchId: 1, message: 'test', users: [{ churchId: 1, email: 'test@google.com' }] }] });
const church = await Church.findOneAndUpdate({ events: { $elemMatch: { users: { $not: { $elemMatch: { email: 'test2@google.com' } } } } } }, { $addToSet: { 'events.$.users': { churchId: 1, email: 'test2@google.com' } } }, { new: true });
assert.equal(church.events.length, 1); assert.equal(church.events[0].users.length, 2); assert.equal(church.events[0].users[1].email, 'test2@google.com'); assert.ok(church.events[0].users[1].createdAt); });
it('sets createdAt when creating new single nested subdoc (gh-11603)', async function() { const childSchema = new mongoose.Schema( { name: String }, { timestamps: { createdAt: 'created', updatedAt: false }, _id: false } );
const testSchema = new mongoose.Schema({ child: childSchema, age: Number });
const Test = db.model('Test', testSchema);
await Test.create({ age: 10 }); await Test.findOneAndUpdate( { child: { $exists: false } }, { $set: { child: { name: 'Update Creation' } } } );
let updatedParent = await Test.findOne({ age: 10 }); assert.ok(updatedParent.child.created instanceof Date);
await Test.create({ age: 12 }); const parentToChange = await Test.findOne({ child: { $exists: false } });
parentToChange.child = { name: 'Save Creation' }; await parentToChange.save();
updatedParent = await Test.findOne({ age: 12 }); assert.ok(updatedParent.child.created instanceof Date); const date = updatedParent.child.created;
updatedParent.child.name = 'test update'; await updatedParent.save();
updatedParent = await Test.findOne({ age: 12 }); assert.ok(updatedParent.child.created instanceof Date); assert.strictEqual(updatedParent.child.created.valueOf(), date.valueOf()); });
it('sets timestamps on sub-schema if parent schema does not have timestamps: true (gh-12119)', async function() { // `timestamps` option set to true on deepest sub document const ConditionSchema = new mongoose.Schema({ kind: String, amount: Number }, { timestamps: true });
// no `timestamps` option defined const ProfileSchema = new mongoose.Schema({ conditions: [ConditionSchema] });
const UserSchema = new mongoose.Schema({ name: String, profile: { type: ProfileSchema } }, { timestamps: true });
const User = db.model('User', UserSchema);
const res = await User.findOneAndUpdate( { name: 'test' }, { $set: { profile: { conditions: [{ kind: 'price', amount: 10 }] } } }, { upsert: true, returnDocument: 'after' } );
assert.ok(res.profile.conditions[0].createdAt); assert.ok(res.profile.conditions[0].updatedAt); });
it('works with insertMany() and embedded discriminators (gh-12150)', async function() { const AssetSchema = new Schema({ url: String, size: String }, { timestamps: true }); const HeaderSectionSchema = new Schema({ title: String, image: AssetSchema });
// Abstract section const BaseSectionSchema = new Schema({ isVisible: Boolean }, { discriminatorKey: 'kind' });
// Main Schema const PageSchema = new Schema({ sections: [BaseSectionSchema] // Same error without the array "sections: BaseSectionSchema" }, { timestamps: true });
const sections = PageSchema.path('sections'); sections.discriminator('header', HeaderSectionSchema);
const Test = db.model('Test', PageSchema);
await Test.insertMany([{ sections: { isVisible: true, kind: 'header', title: 'h1' } }]);
const doc = await Test.findOne(); assert.equal(doc.sections.length, 1); assert.equal(doc.sections[0].title, 'h1'); });
it('findOneAndUpdate creates subdocuments with timestamps in correct order (gh-12475)', async function() { const testSchema = new Schema( { uuid: String, addresses: [new Schema({ location: String }, { timestamps: true })] }, { timestamps: true } );
const Test = db.model('Test', testSchema);
const item = new Test({ uuid: '123', addresses: [{ location: 'earth' }] }); await item.save();
const newItem = await Test.findOneAndUpdate({ uuid: '123' }, { uuid: '456', $push: { addresses: { location: 'earth' } } }, { upsert: true, new: true, runValidators: true });
for (const address of newItem.addresses) { const keys = Object.keys(address.toObject()); assert.deepStrictEqual(keys, ['location', '_id', 'createdAt', 'updatedAt']); } });});
async function delay(ms) { await new Promise((resolve) => setTimeout(resolve, ms));}
mongoose

Version Info

Tagged at
a year ago