-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
types.map.test.js
1105 lines (891 loc) · 28.6 KB
/
types.map.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
'use strict';
/**
* Module dependencies.
*/
const start = require('./common');
const SchemaMapOptions = require('../lib/options/SchemaMapOptions');
const assert = require('assert');
const mongoose = start.mongoose;
const Schema = mongoose.Schema;
/**
* Test.
*/
describe('Map', 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));
it('validation', async function() {
const nestedValidateCalls = [];
const validateCalls = [];
const TestSchema = new mongoose.Schema({
v: {
type: Map,
of: {
type: Number,
validate: function(v) {
nestedValidateCalls.push(v);
return v < 4;
}
},
validate: function(v) {
validateCalls.push(v);
return true;
}
}
});
assert.ok(TestSchema.path('v').options instanceof SchemaMapOptions);
const Test = db.model('MapTest', TestSchema);
const doc = await Test.create({ v: { x: 1 } });
assert.deepEqual(nestedValidateCalls, [1]);
assert.equal(validateCalls.length, 1);
assert.equal(validateCalls[0].get('x'), 1);
assert.ok(doc.v instanceof Map);
let threw = false;
try {
await Test.create({ v: { notA: 'number' } });
} catch (error) {
threw = true;
assert.ok(!error.errors['v']);
assert.ok(error.errors['v.notA']);
}
assert.ok(threw);
doc.v.set('y', 5);
threw = false;
try {
await doc.save();
} catch (error) {
threw = true;
assert.ok(!error.errors['v']);
assert.ok(error.errors['v.y']);
}
assert.ok(threw);
});
it('deep set', function(done) {
const userSchema = new mongoose.Schema({
socialMediaHandles: {
type: Schema.Types.Map,
of: String
}
});
const User = db.model('MapDeepSet', userSchema);
const user = new User({ socialMediaHandles: {} });
user.set('socialMediaHandles.github', 'vkarpov15');
assert.equal(user.socialMediaHandles.get('github'), 'vkarpov15');
assert.equal(user.get('socialMediaHandles.github'), 'vkarpov15');
done();
});
it('supports delete() (gh-7743)', async function() {
const Person = db.model('gh7743', new mongoose.Schema({
name: String,
fact: {
type: Map,
default: {},
of: Boolean
}
}));
const person = new Person({
name: 'Arya Stark',
fact: {
cool: true,
girl: true,
killer: true
}
});
await person.save();
assert.strictEqual(person.fact.get('killer'), true);
person.fact.delete('killer');
assert.deepStrictEqual(person.$__delta()[1], { $unset: { 'fact.killer': 1 } });
assert.deepStrictEqual(Array.from(person.fact.keys()).sort(), ['cool', 'girl']);
assert.strictEqual(person.fact.get('killer'), undefined);
await person.save();
const queryPerson = await Person.findOne({ name: 'Arya Stark' });
assert.strictEqual(queryPerson.fact.get('killer'), undefined);
});
it('query casting', async function() {
const TestSchema = new mongoose.Schema({
v: {
type: Map,
of: Number
}
});
const Test = db.model('MapQueryTest', TestSchema);
const docs = await Test.create([
{ v: { n: 1 } },
{ v: { n: 2 } }
]);
let res = await Test.find({ 'v.n': 1 });
assert.equal(res.length, 1);
res = await Test.find({ v: { n: 2 } });
assert.equal(res.length, 1);
await Test.updateOne({ _id: docs[1]._id }, { 'v.n': 3 });
res = await Test.find({ v: { n: 3 } });
assert.equal(res.length, 1);
let threw = false;
try {
await Test.updateOne({ _id: docs[1]._id }, { 'v.n': 'not a number' });
} catch (error) {
threw = true;
assert.equal(error.name, 'CastError');
}
assert.ok(threw);
res = await Test.find({ v: { n: 3 } });
assert.equal(res.length, 1);
});
it('defaults', async function() {
const TestSchema = new mongoose.Schema({
n: Number,
m: {
type: Map,
of: Number,
default: { bacon: 2, eggs: 6 }
}
});
const Test = db.model('MapDefaultsTest', TestSchema);
const doc = new Test({});
assert.ok(doc.m instanceof Map);
assert.deepEqual(Array.from(doc.toObject().m.keys()), ['bacon', 'eggs']);
await Test.updateOne({}, { n: 1 }, { upsert: true });
const saved = await Test.findOne({ n: 1 });
assert.ok(saved);
assert.deepEqual(Array.from(saved.toObject().m.keys()),
['bacon', 'eggs']);
});
it('validation', async function() {
const TestSchema = new mongoose.Schema({
ratings: {
type: Map,
of: {
type: Number,
min: 1,
max: 10
}
}
});
const Test = db.model('MapValidationTest', TestSchema);
const doc = new Test({ ratings: { github: 11 } });
assert.ok(doc.ratings instanceof Map);
let threw = false;
try {
await doc.save();
} catch (err) {
threw = true;
assert.ok(err.errors['ratings.github']);
}
assert.ok(threw);
doc.ratings.set('github', 8);
// Shouldn't throw
await doc.save();
threw = false;
try {
await Test.updateOne({}, { $set: { 'ratings.github': 11 } }, {
runValidators: true
});
} catch (err) {
threw = true;
assert.ok(err.errors['ratings.github']);
}
assert.ok(threw);
});
it('with single nested subdocs', async function() {
const TestSchema = new mongoose.Schema({
m: {
type: Map,
of: new mongoose.Schema({ n: Number }, { _id: false, id: false })
}
});
const Test = db.model('MapEmbeddedTest', TestSchema);
let doc = new Test({ m: { bacon: { n: 2 } } });
await doc.save();
assert.ok(doc.m instanceof Map);
assert.deepEqual(doc.toObject().m.get('bacon').toObject(), { n: 2 });
doc.m.get('bacon').n = 4;
await doc.save();
assert.deepEqual(doc.toObject().m.get('bacon').toObject(), { n: 4 });
doc = await Test.findById(doc._id);
assert.deepEqual(doc.toObject().m.get('bacon').toObject(), { n: 4 });
});
describe('populate', function() {
it('populate individual path', async function() {
const UserSchema = new mongoose.Schema({
keys: {
type: Map,
of: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Test'
}
}
});
const KeySchema = new mongoose.Schema({ key: String });
const User = db.model('User', UserSchema);
const Key = db.model('Test', KeySchema);
const key = await Key.create({ key: 'abc123' });
const key2 = await Key.create({ key: 'key' });
const doc = await User.create({ keys: { github: key._id } });
const populated = await User.findById(doc).populate('keys.github');
assert.equal(populated.keys.get('github').key, 'abc123');
populated.keys.set('twitter', key2._id);
await populated.save();
const rawDoc = await User.collection.findOne({ _id: doc._id });
assert.deepEqual(rawDoc.keys, { github: key._id, twitter: key2._id });
});
it('populate entire map', async function() {
const UserSchema = new mongoose.Schema({
apiKeys: {
type: Map,
of: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Test'
}
}
});
const KeySchema = new mongoose.Schema({ key: String });
const User = db.model('User', UserSchema);
const Key = db.model('Test', KeySchema);
const key = await Key.create({ key: 'abc123' });
const key2 = await Key.create({ key: 'key' });
const doc = await User.create({ apiKeys: { github: key._id, twitter: key2._id } });
const populated = await User.findById(doc).populate('apiKeys');
assert.equal(populated.apiKeys.get('github').key, 'abc123');
assert.equal(populated.apiKeys.get('twitter').key, 'key');
});
it('populate entire map in doc', async function() {
const UserSchema = new mongoose.Schema({
apiKeys: {
type: Map,
of: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Test'
}
}
});
const KeySchema = new mongoose.Schema({ key: String });
const User = db.model('User', UserSchema);
const Key = db.model('Test', KeySchema);
const key = await Key.create({ key: 'abc123' });
const key2 = await Key.create({ key: 'key' });
const doc = await User.create({ apiKeys: { github: key._id, twitter: key2._id } });
const _doc = await User.findById(doc);
await _doc.populate('apiKeys');
assert.equal(_doc.apiKeys.get('github').key, 'abc123');
assert.equal(_doc.apiKeys.get('twitter').key, 'key');
});
it('avoid populating as map if populate on obj (gh-6460) (gh-8157)', async function() {
const UserSchema = new mongoose.Schema({
apiKeys: {}
});
const KeySchema = new mongoose.Schema({ key: String });
const User = db.model('User', UserSchema);
const Key = db.model('Test', KeySchema);
const key = await Key.create({ key: 'abc123' });
const key2 = await Key.create({ key: 'key' });
const doc = await User.create({ apiKeys: { github: key._id, twitter: key2._id } });
const populated = await User.findById(doc).populate({
path: 'apiKeys',
skipInvalidIds: true
});
assert.ok(!(populated.apiKeys instanceof Map));
assert.ok(!Array.isArray(populated.apiKeys));
});
it('handles setting populated path to doc and then saving (gh-7745)', async function() {
const Scene = db.model('Test', new mongoose.Schema({
name: String
}));
const Event = db.model('Event', new mongoose.Schema({
scenes: {
type: Map,
default: {},
of: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Test'
}
}
}));
const foo = await Scene.create({ name: 'foo' });
let event = await Event.create({ scenes: { foo: foo._id } });
event = await Event.findById(event).populate('scenes.$*');
const bar = await Scene.create({ name: 'bar' });
event.scenes.set('bar', bar);
await event.save();
event = await Event.findById(event).populate('scenes.$*');
assert.ok(event.scenes.has('bar'));
assert.equal(event.scenes.get('bar').name, 'bar');
});
it('handles populating path of subdoc (gh-9359)', async function() {
const bookSchema = Schema({
author: {
type: 'ObjectId',
ref: 'Person'
},
title: String
}, { _id: false });
const schema = Schema({
books: {
type: Map,
of: bookSchema
}
});
const Person = db.model('Person', Schema({ name: String }));
const Test = db.model('Test', schema);
const person = await Person.create({ name: 'Ian Fleming' });
await Test.create({
books: {
key1: {
title: 'Casino Royale',
author: person._id
}
}
});
let doc = await Test.findOne().populate('books.$*.author');
assert.equal(doc.books.get('key1').author.name, 'Ian Fleming');
doc.books.set('key2', { title: 'Live and Let Die', author: person._id });
await doc.save();
doc = await Test.findOne().populate('books.$*.author');
assert.equal(doc.books.get('key2').author.name, 'Ian Fleming');
});
});
it('discriminators', async function() {
const TestSchema = new mongoose.Schema({
n: Number
});
const Test = db.model('Test', TestSchema);
const Disc = Test.discriminator('D', new mongoose.Schema({
m: {
type: Map,
of: Number
}
}));
const doc = new Disc({ m: { test: 1 } });
assert.ok(doc.m instanceof Map);
assert.deepEqual(Array.from(doc.toObject().m.keys()), ['test']);
await doc.save();
const fromDb = await Disc.findOne({ 'm.test': 1 });
assert.ok(fromDb);
assert.equal(fromDb._id.toHexString(), doc._id.toHexString());
});
it('embedded discriminators', async function() {
const EmployeeSchema = new mongoose.Schema({
name: String
}, { _id: false, id: false });
const DepartmentSchema = new mongoose.Schema({
employees: [EmployeeSchema]
});
DepartmentSchema.path('employees').discriminator('Sales', new mongoose.Schema({
clients: [String]
}, { _id: false, id: false }));
DepartmentSchema.path('employees').discriminator('Engineering', new mongoose.Schema({
apiKeys: {
type: Map,
of: String
}
}, { _id: false, id: false }));
const Department = db.model('Test', DepartmentSchema);
const dept = new Department({
employees: [
{ __t: 'Sales', name: 'E1', clients: ['test1', 'test2'] },
{ __t: 'Engineering', name: 'E2', apiKeys: { github: 'test3' } }
]
});
assert.deepEqual(dept.toObject().employees[0],
{ __t: 'Sales', name: 'E1', clients: ['test1', 'test2'] });
assert.deepEqual(Array.from(dept.toObject().employees[1].apiKeys.values()),
['test3']);
await dept.save();
let fromDb = await Department.findOne({ 'employees.apiKeys.github': 'test3' });
assert.ok(fromDb);
dept.employees[1].apiKeys.set('github', 'test4');
await dept.save();
fromDb = await Department.findOne({ 'employees.apiKeys.github': 'test4' });
assert.ok(fromDb);
});
it('toJSON seralizes map paths (gh-6478)', async function() {
const schema = new mongoose.Schema({
str: {
type: Map,
of: String
},
num: {
type: Map,
of: Number
}
});
const Test = db.model('Test', schema);
const test = new Test({
str: {
testing: '123'
},
num: {
testing: 456
}
});
assert.deepEqual(test.str.toJSON(), { testing: '123' });
assert.deepEqual(test.num.toJSON(), { testing: 456 });
await test.save();
const found = await Test.findOne();
assert.deepEqual(found.str.toJSON(), { testing: '123' });
assert.deepEqual(found.num.toJSON(), { testing: 456 });
});
it('updating map doesnt crash (gh-6750)', async function() {
const Schema = mongoose.Schema;
const User = db.model('User', {
maps: { type: Map, of: String, default: {} }
});
const Post = db.model('BlogPost', {
user: { type: Schema.Types.ObjectId, ref: 'User' }
});
const user = await User.create({});
const doc = await Post.
findOneAndUpdate({}, { user: user }, { upsert: true, new: true });
assert.ok(doc);
assert.equal(doc.user.toHexString(), user._id.toHexString());
});
it('works with sub doc hooks (gh-6938)', async function() {
const Schema = mongoose.Schema;
let subDocHooksCalledTimes = 0;
let mapChildHooksCalledTimes = 0;
const mapChildSchema = new Schema({
y: Number
});
mapChildSchema.pre('save', function() {
mapChildHooksCalledTimes++;
});
const mapSchema = new Schema({
x: String,
child: mapChildSchema
});
mapSchema.pre('save', function() {
subDocHooksCalledTimes++;
});
const schema = new Schema({
widgets: {
type: Map,
of: mapSchema
}
});
const Test = db.model('Test', schema);
const test = new Test({ widgets: { one: { x: 'a' } } });
test.widgets.set('two', { x: 'b' });
test.widgets.set('three', { x: 'c', child: { y: 2018 } });
await test.save();
assert.strictEqual(subDocHooksCalledTimes, 3);
assert.strictEqual(mapChildHooksCalledTimes, 1);
});
it('array of mixed maps (gh-6995)', function() {
const Model = db.model('Test', new Schema({ arr: [Map] }));
return Model.create({ arr: [{ a: 1 }] }).
then(doc => {
assert.deepEqual(doc.toObject().arr, [new Map([['a', 1]])]);
});
});
it('only runs setters once on init (gh-7272)', async function() {
let setterContext = [];
function set(v) {
setterContext.push(this);
return v;
}
const ChildSchema = new mongoose.Schema({
age: {
type: Number,
set: set
}
});
const ParentSchema = new mongoose.Schema({
name: String,
children: {
type: Map,
of: ChildSchema
}
});
const Parent = db.model('Parent', ParentSchema);
await Parent.create({ children: { luke: { age: 30 } } });
setterContext = [];
await Parent.findOne({ 'children.luke.age': 30 });
assert.equal(setterContext.length, 1);
assert.ok(setterContext[0] instanceof mongoose.Query);
});
it('init then set marks correct path as modified (gh-7321)', async function() {
const childSchema = new mongoose.Schema({ name: String });
const parentSchema = new mongoose.Schema({
children: {
type: Map,
of: childSchema
}
});
const Parent = db.model('Parent', parentSchema);
const first = await Parent.create({
children: {
one: { name: 'foo' }
}
});
let loaded = await Parent.findById(first.id);
assert.equal(loaded.get('children.one.name'), 'foo');
loaded.children.get('one').set('name', 'bar');
await loaded.save();
loaded = await Parent.findById(first.id);
assert.equal(loaded.get('children.one.name'), 'bar');
});
it('nested maps (gh-7630)', async function() {
const schema = new mongoose.Schema({
describe: {
type: Map,
of: Map,
default: {}
}
});
const GoodsInfo = db.model('Test', schema);
let goodsInfo = new GoodsInfo();
goodsInfo.describe = new Map();
goodsInfo.describe.set('brand', new Map([['en', 'Hermes']]));
await goodsInfo.save();
goodsInfo = await GoodsInfo.findById(goodsInfo);
assert.equal(goodsInfo.get('describe.brand.en'), 'Hermes');
});
it('get full path in validator with `propsParameter` (gh-7447)', function() {
const calls = [];
const schema = new mongoose.Schema({
myMap: {
type: Map,
of: {
type: String,
validate: {
validator: (v, props) => {
calls.push(props.path);
return v === 'bar';
},
propsParameter: true
}
}
}
});
const Model = db.model('Test', schema);
const doc = new Model({ myMap: { foo: 'bar' } });
assert.equal(calls.length, 0);
assert.ifError(doc.validateSync());
assert.deepEqual(calls, ['myMap.foo']);
return doc.validate().
then(() => {
assert.deepEqual(calls, ['myMap.foo', 'myMap.foo']);
});
});
it('treats `of` as a schema if typeKey is not set (gh-7859)', function() {
const schema = new mongoose.Schema({
myMap: {
type: Map,
of: {
test: { type: String, required: true }
}
}
});
const Model = db.model('Test', schema);
const doc = new Model({ myMap: { foo: {} } });
const err = doc.validateSync();
assert.ok(err);
assert.ok(err.errors['myMap.foo.test'].message.indexOf('required') !== -1,
err.errors['myMap.foo.test'].message);
});
it('works with clone() (gh-8357)', function() {
const childSchema = mongoose.Schema({ name: String });
const schema = mongoose.Schema({
myMap: {
type: Map,
of: childSchema
}
});
const Model = db.model('Test', schema.clone());
const doc = new Model({ myMap: { foo: { name: 'bar' } } });
const err = doc.validateSync();
assert.ifError(err);
});
it('maps of single nested docs with inline _id (gh-8424)', function() {
const childSchema = mongoose.Schema({ name: String });
const schema = mongoose.Schema({
myMap: {
type: Map,
of: {
type: childSchema,
_id: false
}
}
});
const Model = db.model('Test', schema);
const doc = new Model({ myMap: { foo: { name: 'bar' } } });
assert.equal(doc.myMap.get('foo').name, 'bar');
assert.ok(!doc.myMap.get('foo')._id);
});
it('avoids marking path as modified if setting to same value (gh-8652)', async function() {
const childSchema = mongoose.Schema({ name: String }, { _id: false });
const schema = mongoose.Schema({
numMap: {
type: Map,
of: Number
},
docMap: {
type: Map,
of: childSchema
}
});
const Model = db.model('Test', schema);
await Model.create({
numMap: {
answer: 42,
powerLevel: 9001
},
docMap: {
captain: { name: 'Jean-Luc Picard' },
firstOfficer: { name: 'Will Riker' }
}
});
const doc = await Model.findOne();
doc.numMap.set('answer', 42);
doc.numMap.set('powerLevel', 9001);
doc.docMap.set('captain', { name: 'Jean-Luc Picard' });
doc.docMap.set('firstOfficer', { name: 'Will Riker' });
assert.deepEqual(doc.modifiedPaths(), []);
});
it('handles setting map value to spread document (gh-8652)', async function() {
const childSchema = mongoose.Schema({ name: String }, { _id: false });
const schema = mongoose.Schema({
docMap: {
type: Map,
of: childSchema
}
});
const Model = db.model('Test', schema);
await Model.create({
docMap: {
captain: { name: 'Jean-Luc Picard' },
firstOfficer: { name: 'Will Riker' }
}
});
const doc = await Model.findOne();
doc.docMap.set('captain', Object.assign({}, doc.docMap.get('firstOfficer')));
await doc.save();
const fromDb = await Model.findOne();
assert.equal(fromDb.docMap.get('firstOfficer').name, 'Will Riker');
});
it('runs getters on map values (gh-8730)', function() {
const schema = mongoose.Schema({
name: String,
books: {
type: Map,
of: {
type: String,
get: function(v) { return `${v}, by ${this.name}`; }
}
}
});
const Model = db.model('Test', schema);
const doc = new Model({
name: 'Ian Fleming',
books: {
'casino-royale': 'Casino Royale'
}
});
assert.equal(doc.books.get('casino-royale'), 'Casino Royale, by Ian Fleming');
assert.equal(doc.get('books.casino-royale'), 'Casino Royale, by Ian Fleming');
});
it('handles validation of document array with maps and nested paths (gh-8767)', function() {
const subSchema = Schema({
_id: Number,
level2: {
type: Map,
of: Schema({
_id: Number,
level3: {
type: Map,
of: Number,
required: true
}
})
},
otherProps: { test: Number }
});
const mainSchema = Schema({ _id: Number, level1: [subSchema] });
const Test = db.model('Test', mainSchema);
const doc = new Test({
_id: 1,
level1: [
{ _id: 10, level2: { answer: { _id: 101, level3: { value: 42 } } } },
{ _id: 20, level2: { powerLevel: { _id: 201, level3: { value: 9001 } } } }
]
});
return doc.validate();
});
it('persists `.clear()` (gh-9493)', async function() {
const BoardSchema = new Schema({
_id: { type: String },
elements: { type: Map, default: new Map() }
});
const BoardModel = db.model('Test', BoardSchema);
let board = new BoardModel({ _id: 'test' });
board.elements.set('a', 1);
await board.save();
board = await BoardModel.findById('test').exec();
board.elements.clear();
await board.save();
board = await BoardModel.findById('test').exec();
assert.equal(board.elements.size, 0);
});
it('supports `null` in map of subdocuments (gh-9628)', async function() {
const testSchema = new Schema({
messages: { type: Map, of: new Schema({ _id: false, text: String }) }
});
const Test = db.model('Test', testSchema);
let doc = await Test.create({
messages: { prop1: { text: 'test' }, prop2: null }
});
doc = await Test.findById(doc);
assert.deepEqual(doc.messages.get('prop1').toObject(), { text: 'test' });
assert.strictEqual(doc.messages.get('prop2'), null);
assert.ifError(doc.validateSync());
});
it('tracks changes correctly (gh-9811)', async function() {
const SubSchema = Schema({
myValue: {
type: String
}
}, { _id: false });
const schema = Schema({
myMap: {
type: Map,
of: {
type: SubSchema
}
// required: true
}
}, { minimize: false, collection: 'test' });
const Model = db.model('Test', schema);
const doc = await Model.create({
myMap: new Map()
});
doc.myMap.set('abc', { myValue: 'some value' });
const changes = doc.getChanges();
assert.ok(!changes.$unset);
assert.deepEqual(changes, { $set: { 'myMap.abc': { myValue: 'some value' } } });
});
it('handles map of arrays (gh-9813)', async function() {
const BudgetSchema = new mongoose.Schema({
budgeted: {
type: Map,
of: [Number]
}
});
const Budget = db.model('Test', BudgetSchema);
const _id = await Budget.create({
budgeted: new Map([['2020', [100, 200, 300]]])
}).then(doc => doc._id);
const doc = await Budget.findById(_id);
doc.budgeted.get('2020').set(2, 10);
assert.deepEqual(doc.getChanges(), { $set: { 'budgeted.2020.2': 10 } });
await doc.save();
const res = await Budget.findOne();
assert.deepEqual(res.toObject().budgeted.get('2020'), [100, 200, 10]);
});
it('can populate map of subdocs with doc array using ref function (gh-10584)', async function() {
const Person = db.model('Person', Schema({ name: String }));
const Book = db.model('Book', Schema({ title: String }));
const schema = new Schema({
myMap: {
type: Map,
of: {
modelId: String,
data: [{
_id: {
type: mongoose.ObjectId,
ref: doc => doc.$parent().modelId
}
}]