deno.land / x / mongoose@6.7.5 / lib / document.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
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
'use strict';
/*! * Module dependencies. */const EventEmitter = require('events').EventEmitter;const InternalCache = require('./internal');const MongooseError = require('./error/index');const MixedSchema = require('./schema/mixed');const ObjectExpectedError = require('./error/objectExpected');const ObjectParameterError = require('./error/objectParameter');const ParallelValidateError = require('./error/parallelValidate');const Schema = require('./schema');const StrictModeError = require('./error/strict');const ValidationError = require('./error/validation');const ValidatorError = require('./error/validator');const VirtualType = require('./virtualtype');const $__hasIncludedChildren = require('./helpers/projection/hasIncludedChildren');const promiseOrCallback = require('./helpers/promiseOrCallback');const castNumber = require('./cast/number');const applyDefaults = require('./helpers/document/applyDefaults');const cleanModifiedSubpaths = require('./helpers/document/cleanModifiedSubpaths');const compile = require('./helpers/document/compile').compile;const defineKey = require('./helpers/document/compile').defineKey;const flatten = require('./helpers/common').flatten;const flattenObjectWithDottedPaths = require('./helpers/path/flattenObjectWithDottedPaths');const get = require('./helpers/get');const getEmbeddedDiscriminatorPath = require('./helpers/document/getEmbeddedDiscriminatorPath');const getKeysInSchemaOrder = require('./helpers/schema/getKeysInSchemaOrder');const handleSpreadDoc = require('./helpers/document/handleSpreadDoc');const immediate = require('./helpers/immediate');const isDefiningProjection = require('./helpers/projection/isDefiningProjection');const isExclusive = require('./helpers/projection/isExclusive');const inspect = require('util').inspect;const internalToObjectOptions = require('./options').internalToObjectOptions;const markArraySubdocsPopulated = require('./helpers/populate/markArraySubdocsPopulated');const mpath = require('mpath');const queryhelpers = require('./queryhelpers');const utils = require('./utils');const isPromise = require('./helpers/isPromise');
const clone = utils.clone;const deepEqual = utils.deepEqual;const isMongooseObject = utils.isMongooseObject;
const arrayAtomicsBackupSymbol = require('./helpers/symbols').arrayAtomicsBackupSymbol;const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol;const documentArrayParent = require('./helpers/symbols').documentArrayParent;const documentIsModified = require('./helpers/symbols').documentIsModified;const documentModifiedPaths = require('./helpers/symbols').documentModifiedPaths;const documentSchemaSymbol = require('./helpers/symbols').documentSchemaSymbol;const getSymbol = require('./helpers/symbols').getSymbol;const populateModelSymbol = require('./helpers/symbols').populateModelSymbol;const scopeSymbol = require('./helpers/symbols').scopeSymbol;const schemaMixedSymbol = require('./schema/symbols').schemaMixedSymbol;const parentPaths = require('./helpers/path/parentPaths');
let DocumentArray;let MongooseArray;let Embedded;
const specialProperties = utils.specialProperties;
/** * The core Mongoose document constructor. You should not call this directly, * the Mongoose [Model constructor](./api.html#Model) calls this for you. * * @param {Object} obj the values to set * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data * @param {Object} [options] various configuration options for the document * @param {Boolean} [options.defaults=true] if `false`, skip applying default values to this document. * @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#class-eventemitter * @event `init`: Emitted on a document after it has been retrieved from the db and fully hydrated by Mongoose. * @event `save`: Emitted when the document is successfully saved * @api private */function Document(obj, fields, skipId, options) { if (typeof skipId === 'object' && skipId != null) { options = skipId; skipId = options.skipId; } options = Object.assign({}, options); // Support `browserDocument.js` syntax if (this.$__schema == null) { const _schema = utils.isObject(fields) && !fields.instanceOfSchema ? new Schema(fields) : fields; this.$__setSchema(_schema); fields = skipId; skipId = options; options = arguments[4] || {}; } this.$__ = new InternalCache(); // Avoid setting `isNew` to `true`, because it is `true` by default if (options.isNew != null && options.isNew !== true) { this.$isNew = options.isNew; } if (options.priorDoc != null) { this.$__.priorDoc = options.priorDoc; } if (skipId) { this.$__.skipId = skipId; } if (obj != null && typeof obj !== 'object') { throw new ObjectParameterError(obj, 'obj', 'Document'); } let defaults = true; if (options.defaults !== undefined) { this.$__.defaults = options.defaults; defaults = options.defaults; } const schema = this.$__schema; if (typeof fields === 'boolean' || fields === 'throw') { if (fields !== true) { this.$__.strictMode = fields; } fields = undefined; } else if (schema.options.strict !== true) { this.$__.strictMode = schema.options.strict; } const requiredPaths = schema.requiredPaths(true); for (const path of requiredPaths) { this.$__.activePaths.require(path); } let exclude = null; // determine if this doc is a result of a query with // excluded fields if (utils.isPOJO(fields) && Object.keys(fields).length > 0) { exclude = isExclusive(fields); this.$__.selected = fields; this.$__.exclude = exclude; } const hasIncludedChildren = exclude === false && fields ? $__hasIncludedChildren(fields) : null; if (this._doc == null) { this.$__buildDoc(obj, fields, skipId, exclude, hasIncludedChildren, false); // By default, defaults get applied **before** setting initial values // Re: gh-6155 if (defaults) { applyDefaults(this, fields, exclude, hasIncludedChildren, true, null); } } if (obj) { // Skip set hooks if (this.$__original_set) { this.$__original_set(obj, undefined, true, options); } else { this.$set(obj, undefined, true, options); } if (obj instanceof Document) { this.$isNew = obj.$isNew; } } // Function defaults get applied **after** setting initial values so they // see the full doc rather than an empty one, unless they opt out. // Re: gh-3781, gh-6155 if (options.willInit && defaults) { if (options.skipDefaults) { this.$__.skipDefaults = options.skipDefaults; } } else if (defaults) { applyDefaults(this, fields, exclude, hasIncludedChildren, false, options.skipDefaults); } if (!this.$__.strictMode && obj) { const _this = this; const keys = Object.keys(this._doc); keys.forEach(function(key) { // Avoid methods, virtuals, existing fields, and `$` keys. The latter is to avoid overwriting // Mongoose internals. if (!(key in schema.tree) && !(key in schema.methods) && !(key in schema.virtuals) && !key.startsWith('$')) { defineKey({ prop: key, subprops: null, prototype: _this }); } }); } applyQueue(this);}
/** * Boolean flag specifying if the document is new. If you create a document * using `new`, this document will be considered "new". `$isNew` is how * Mongoose determines whether `save()` should use `insertOne()` to create * a new document or `updateOne()` to update an existing document. * * #### Example: * * const user = new User({ name: 'John Smith' }); * user.$isNew; // true * * await user.save(); // Sends an `insertOne` to MongoDB * * On the other hand, if you load an existing document from the database * using `findOne()` or another [query operation](/docs/queries.html), * `$isNew` will be false. * * #### Example: * * const user = await User.findOne({ name: 'John Smith' }); * user.$isNew; // false * * Mongoose sets `$isNew` to `false` immediately after `save()` succeeds. * That means Mongoose sets `$isNew` to false **before** `post('save')` hooks run. * In `post('save')` hooks, `$isNew` will be `false` if `save()` succeeded. * * #### Example: * * userSchema.post('save', function() { * this.$isNew; // false * }); * await User.create({ name: 'John Smith' }); * * For subdocuments, `$isNew` is true if either the parent has `$isNew` set, * or if you create a new subdocument. * * #### Example: * * // Assume `Group` has a document array `users` * const group = await Group.findOne(); * group.users[0].$isNew; // false * * group.users.push({ name: 'John Smith' }); * group.users[1].$isNew; // true * * @api public * @property $isNew * @memberOf Document * @instance */Object.defineProperty(Document.prototype, 'isNew', { get: function() { return this.$isNew; }, set: function(value) { this.$isNew = value; }});
/** * Hash containing current validation errors. * * @api public * @property errors * @memberOf Document * @instance */Object.defineProperty(Document.prototype, 'errors', { get: function() { return this.$errors; }, set: function(value) { this.$errors = value; }});
/*! * ignore */Document.prototype.$isNew = true;
/*! * Document exposes the NodeJS event emitter API, so you can use * `on`, `once`, etc. */utils.each( ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners', 'removeAllListeners', 'addListener'], function(emitterFn) { Document.prototype[emitterFn] = function() { // Delay creating emitter until necessary because emitters take up a lot of memory, // especially for subdocuments. if (!this.$__.emitter) { if (emitterFn === 'emit') { return; } this.$__.emitter = new EventEmitter(); this.$__.emitter.setMaxListeners(0); } return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments); }; Document.prototype[`$${emitterFn}`] = Document.prototype[emitterFn]; });Document.prototype.constructor = Document;
for (const i in EventEmitter.prototype) { Document[i] = EventEmitter.prototype[i];}
/** * The document's internal schema. * * @api private * @property schema * @memberOf Document * @instance */Document.prototype.$__schema;
/** * The document's schema. * * @api public * @property schema * @memberOf Document * @instance */Document.prototype.schema;
/** * Empty object that you can use for storing properties on the document. This * is handy for passing data to middleware without conflicting with Mongoose * internals. * * #### Example: * * schema.pre('save', function() { * // Mongoose will set `isNew` to `false` if `save()` succeeds * this.$locals.wasNew = this.isNew; * }); * * schema.post('save', function() { * // Prints true if `isNew` was set before `save()` * console.log(this.$locals.wasNew); * }); * * @api public * @property $locals * @memberOf Document * @instance */Object.defineProperty(Document.prototype, '$locals', { configurable: false, enumerable: false, get: function() { if (this.$__.locals == null) { this.$__.locals = {}; } return this.$__.locals; }, set: function(v) { this.$__.locals = v; }});
/** * Legacy alias for `$isNew`. * * @api public * @property isNew * @memberOf Document * @see $isNew #document_Document-$isNew * @instance */Document.prototype.isNew;
/** * Set this property to add additional query filters when Mongoose saves this document and `isNew` is false. * * #### Example: * * // Make sure `save()` never updates a soft deleted document. * schema.pre('save', function() { * this.$where = { isDeleted: false }; * }); * * @api public * @property $where * @memberOf Document * @instance */Object.defineProperty(Document.prototype, '$where', { configurable: false, enumerable: false, writable: true});
/** * The string version of this documents _id. * * #### Note: * * This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time. * * new Schema({ name: String }, { id: false }); * * @api public * @see Schema options /docs/guide.html#options * @property id * @memberOf Document * @instance */Document.prototype.id;
/** * Hash containing current validation $errors. * * @api public * @property $errors * @memberOf Document * @instance */Document.prototype.$errors;
/** * A string containing the current operation that Mongoose is executing * on this document. May be `null`, `'save'`, `'validate'`, or `'remove'`. * * #### Example: * * const doc = new Model({ name: 'test' }); * doc.$op; // null * * const promise = doc.save(); * doc.$op; // 'save' * * await promise; * doc.$op; // null * * @api public * @property $op * @memberOf Document * @instance */Object.defineProperty(Document.prototype, '$op', { get: function() { return this.$__.op || null; }, set: function(value) { this.$__.op = value; }});
/*! * ignore */function $applyDefaultsToNested(val, path, doc) { if (val == null) { return; } flattenObjectWithDottedPaths(val); const paths = Object.keys(doc.$__schema.paths); const plen = paths.length; const pathPieces = path.indexOf('.') === -1 ? [path] : path.split('.'); for (let i = 0; i < plen; ++i) { let curPath = ''; const p = paths[i]; if (!p.startsWith(path + '.')) { continue; } const type = doc.$__schema.paths[p]; const pieces = type.splitPath().slice(pathPieces.length); const len = pieces.length; if (type.defaultValue === void 0) { continue; } let cur = val; for (let j = 0; j < len; ++j) { if (cur == null) { break; } const piece = pieces[j]; if (j === len - 1) { if (cur[piece] !== void 0) { break; } try { const def = type.getDefault(doc, false); if (def !== void 0) { cur[piece] = def; } } catch (err) { doc.invalidate(path + '.' + curPath, err); break; } break; } curPath += (!curPath.length ? '' : '.') + piece; cur[piece] = cur[piece] || {}; cur = cur[piece]; } }}
/** * Builds the default doc structure * * @param {Object} obj * @param {Object} [fields] * @param {Boolean} [skipId] * @param {Boolean} [exclude] * @param {Object} [hasIncludedChildren] * @api private * @method $__buildDoc * @memberOf Document * @instance */Document.prototype.$__buildDoc = function(obj, fields, skipId, exclude, hasIncludedChildren) { const doc = {}; const paths = Object.keys(this.$__schema.paths). // Don't build up any paths that are underneath a map, we don't know // what the keys will be filter(p => !p.includes('$*')); const plen = paths.length; let ii = 0; for (; ii < plen; ++ii) { const p = paths[ii]; if (p === '_id') { if (skipId) { continue; } if (obj && '_id' in obj) { continue; } } const path = this.$__schema.paths[p].splitPath(); const len = path.length; const last = len - 1; let curPath = ''; let doc_ = doc; let included = false; for (let i = 0; i < len; ++i) { const piece = path[i]; if (!curPath.length) { curPath = piece; } else { curPath += '.' + piece; } // support excluding intermediary levels if (exclude === true) { if (curPath in fields) { break; } } else if (exclude === false && fields && !included) { if (curPath in fields) { included = true; } else if (!hasIncludedChildren[curPath]) { break; } } if (i < last) { doc_ = doc_[piece] || (doc_[piece] = {}); } } } this._doc = doc;};
/*! * Converts to POJO when you use the document for querying */Document.prototype.toBSON = function() { return this.toObject(internalToObjectOptions);};
/** * Initializes the document without setters or marking anything modified. * * Called internally after a document is returned from mongodb. Normally, * you do **not** need to call this function on your own. * * This function triggers `init` [middleware](/docs/middleware.html). * Note that `init` hooks are [synchronous](/docs/middleware.html#synchronous). * * @param {Object} doc document returned by mongo * @param {Object} [opts] * @param {Function} [fn] * @api public * @memberOf Document * @instance */Document.prototype.init = function(doc, opts, fn) { if (typeof opts === 'function') { fn = opts; opts = null; } this.$__init(doc, opts); if (fn) { fn(null, this); } return this;};
/** * Alias for [`.init`](#document_Document-init) * * @api public */Document.prototype.$init = function() { return this.constructor.prototype.init.apply(this, arguments);};
/** * Internal "init" function * * @param {Document} doc * @param {Object} [opts] * @returns {Document} this * @api private */Document.prototype.$__init = function(doc, opts) { this.$isNew = false; opts = opts || {}; // handle docs with populated paths // If doc._id is not null or undefined if (doc._id != null && opts.populated && opts.populated.length) { const id = String(doc._id); for (const item of opts.populated) { if (item.isVirtual) { this.$populated(item.path, utils.getValue(item.path, doc), item); } else { this.$populated(item.path, item._docs[id], item); } if (item._childDocs == null) { continue; } for (const child of item._childDocs) { if (child == null || child.$__ == null) { continue; } child.$__.parent = this; } item._childDocs = []; } } init(this, doc, this._doc, opts); markArraySubdocsPopulated(this, opts.populated); this.$emit('init', this); this.constructor.emit('init', this); const hasIncludedChildren = this.$__.exclude === false && this.$__.selected ? $__hasIncludedChildren(this.$__.selected) : null; applyDefaults(this, this.$__.selected, this.$__.exclude, hasIncludedChildren, false, this.$__.skipDefaults); return this;};
/** * Init helper. * * @param {Object} self document instance * @param {Object} obj raw mongodb doc * @param {Object} doc object we are initializing * @param {Object} [opts] Optional Options * @param {Boolean} [opts.setters] Call `applySetters` instead of `cast` * @param {String} [prefix] Prefix to add to each path * @api private */function init(self, obj, doc, opts, prefix) { prefix = prefix || ''; const keys = Object.keys(obj); const len = keys.length; let schemaType; let path; let i; let index = 0; const strict = self.$__.strictMode; const docSchema = self.$__schema; while (index < len) { _init(index++); } function _init(index) { i = keys[index]; path = prefix + i; schemaType = docSchema.path(path); // Should still work if not a model-level discriminator, but should not be // necessary. This is *only* to catch the case where we queried using the // base model and the discriminated model has a projection if (docSchema.$isRootDiscriminator && !self.$__isSelected(path)) { return; } if (!schemaType && utils.isPOJO(obj[i])) { // assume nested object if (!doc[i]) { doc[i] = {}; if (!strict && !(i in docSchema.tree) && !(i in docSchema.methods) && !(i in docSchema.virtuals)) { self[i] = doc[i]; } } init(self, obj[i], doc[i], opts, path + '.'); } else if (!schemaType) { doc[i] = obj[i]; if (!strict && !prefix) { self[i] = obj[i]; } } else { // Retain order when overwriting defaults if (doc.hasOwnProperty(i) && obj[i] !== void 0) { delete doc[i]; } if (obj[i] === null) { doc[i] = schemaType._castNullish(null); } else if (obj[i] !== undefined) { const wasPopulated = obj[i].$__ == null ? null : obj[i].$__.wasPopulated; if (schemaType && !wasPopulated) { try { if (opts && opts.setters) { // Call applySetters with `init = false` because otherwise setters are a noop const overrideInit = false; doc[i] = schemaType.applySetters(obj[i], self, overrideInit); } else { doc[i] = schemaType.cast(obj[i], self, true); } } catch (e) { self.invalidate(e.path, new ValidatorError({ path: e.path, message: e.message, type: 'cast', value: e.value, reason: e })); } } else { doc[i] = obj[i]; } } // mark as hydrated if (!self.$isModified(path)) { self.$__.activePaths.init(path); } } }}
/** * Sends an update command with this document `_id` as the query selector. * * #### Example: * * weirdCar.update({ $inc: { wheels:1 } }, { w: 1 }, callback); * * #### Valid options: * * - same as in [Model.update](#model_Model-update) * * @see Model.update #model_Model-update * @param {...Object} ops * @param {Object} [options] * @param {Function} [callback] * @return {Query} this * @api public * @memberOf Document * @instance */Document.prototype.update = function update() { const args = [...arguments]; args.unshift({ _id: this._id }); const query = this.constructor.update.apply(this.constructor, args); if (this.$session() != null) { if (!('session' in query.options)) { query.options.session = this.$session(); } } return query;};
/** * Sends an updateOne command with this document `_id` as the query selector. * * #### Example: * * weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback); * * #### Valid options: * * - same as in [Model.updateOne](#model_Model-updateOne) * * @see Model.updateOne #model_Model-updateOne * @param {Object} doc * @param {Object} [options] optional see [`Query.prototype.setOptions()`](https://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and the [Mongoose lean tutorial](/docs/tutorials/lean.html). * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](https://mongoosejs.com/docs/guide.html#strict) * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. * @param {Function} [callback] * @return {Query} * @api public * @memberOf Document * @instance */Document.prototype.updateOne = function updateOne(doc, options, callback) { const query = this.constructor.updateOne({ _id: this._id }, doc, options); const self = this; query.pre(function queryPreUpdateOne(cb) { self.constructor._middleware.execPre('updateOne', self, [self], cb); }); query.post(function queryPostUpdateOne(cb) { self.constructor._middleware.execPost('updateOne', self, [self], {}, cb); }); if (this.$session() != null) { if (!('session' in query.options)) { query.options.session = this.$session(); } } if (callback != null) { return query.exec(callback); } return query;};
/** * Sends a replaceOne command with this document `_id` as the query selector. * * #### Valid options: * * - same as in [Model.replaceOne](https://mongoosejs.com/docs/api/model.html#model_Model-replaceOne) * * @see Model.replaceOne #model_Model-replaceOne * @param {Object} doc * @param {Object} [options] * @param {Function} [callback] * @return {Query} * @api public * @memberOf Document * @instance */Document.prototype.replaceOne = function replaceOne() { const args = [...arguments]; args.unshift({ _id: this._id }); return this.constructor.replaceOne.apply(this.constructor, args);};
/** * Getter/setter around the session associated with this document. Used to * automatically set `session` if you `save()` a doc that you got from a * query with an associated session. * * #### Example: * * const session = MyModel.startSession(); * const doc = await MyModel.findOne().session(session); * doc.$session() === session; // true * doc.$session(null); * doc.$session() === null; // true * * If this is a top-level document, setting the session propagates to all child * docs. * * @param {ClientSession} [session] overwrite the current session * @return {ClientSession} * @method $session * @api public * @memberOf Document */Document.prototype.$session = function $session(session) { if (arguments.length === 0) { if (this.$__.session != null && this.$__.session.hasEnded) { this.$__.session = null; return null; } return this.$__.session; } if (session != null && session.hasEnded) { throw new MongooseError('Cannot set a document\'s session to a session that has ended. Make sure you haven\'t ' + 'called `endSession()` on the session you are passing to `$session()`.'); } if (session == null && this.$__.session == null) { return; } this.$__.session = session; if (!this.$isSubdocument) { const subdocs = this.$getAllSubdocs(); for (const child of subdocs) { child.$session(session); } } return session;};
/** * Getter/setter around whether this document will apply timestamps by * default when using `save()` and `bulkSave()`. * * #### Example: * * const TestModel = mongoose.model('Test', new Schema({ name: String }, { timestamps: true })); * const doc = new TestModel({ name: 'John Smith' }); * * doc.$timestamps(); // true * * doc.$timestamps(false); * await doc.save(); // Does **not** apply timestamps * * @param {Boolean} [value] overwrite the current session * @return {Document|boolean|undefined} When used as a getter (no argument), a boolean will be returned indicating the timestamps option state or if unset "undefined" will be used, otherwise will return "this" * @method $timestamps * @api public * @memberOf Document */Document.prototype.$timestamps = function $timestamps(value) { if (arguments.length === 0) { if (this.$__.timestamps != null) { return this.$__.timestamps; } if (this.$__schema) { return this.$__schema.options.timestamps; } return undefined; } const currentValue = this.$timestamps(); if (value !== currentValue) { this.$__.timestamps = value; } return this;};
/** * Overwrite all values in this document with the values of `obj`, except * for immutable properties. Behaves similarly to `set()`, except for it * unsets all properties that aren't in `obj`. * * @param {Object} obj the object to overwrite this document with * @method overwrite * @memberOf Document * @instance * @api public * @return {Document} this */Document.prototype.overwrite = function overwrite(obj) { const keys = Array.from(new Set(Object.keys(this._doc).concat(Object.keys(obj)))); for (const key of keys) { if (key === '_id') { continue; } // Explicitly skip version key if (this.$__schema.options.versionKey && key === this.$__schema.options.versionKey) { continue; } if (this.$__schema.options.discriminatorKey && key === this.$__schema.options.discriminatorKey) { continue; } this.$set(key, obj[key]); } return this;};
/** * Alias for `set()`, used internally to avoid conflicts * * @param {String|Object} path path or object of key/vals to set * @param {Any} val the value to set * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes * @param {Object} [options] optionally specify options that modify the behavior of the set * @param {Boolean} [options.merge=false] if true, setting a [nested path](/docs/subdocs.html#subdocuments-versus-nested-paths) will merge existing values rather than overwrite the whole object. So `doc.set('nested', { a: 1, b: 2 })` becomes `doc.set('nested.a', 1); doc.set('nested.b', 2);` * @return {Document} this * @method $set * @memberOf Document * @instance * @api public */Document.prototype.$set = function $set(path, val, type, options) { if (utils.isPOJO(type)) { options = type; type = undefined; } const merge = options && options.merge; const adhoc = type && type !== true; const constructing = type === true; let adhocs; let keys; let i = 0; let pathtype; let key; let prefix; const strict = options && 'strict' in options ? options.strict : this.$__.strictMode; if (adhoc) { adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {}); adhocs[path] = this.$__schema.interpretAsType(path, type, this.$__schema.options); } if (path == null) { [path, val] = [val, path]; } else if (typeof path !== 'string') { // new Document({ key: val }) if (path instanceof Document) { if (path.$__isNested) { path = path.toObject(); } else { path = path._doc; } } if (path == null) { [path, val] = [val, path]; } prefix = val ? val + '.' : ''; keys = getKeysInSchemaOrder(this.$__schema, path); const len = keys.length; // `_skipMinimizeTopLevel` is because we may have deleted the top-level // nested key to ensure key order. const _skipMinimizeTopLevel = options && options._skipMinimizeTopLevel || false; if (len === 0 && _skipMinimizeTopLevel) { delete options._skipMinimizeTopLevel; if (val) { this.$set(val, {}); } return this; } for (let i = 0; i < len; ++i) { key = keys[i]; const pathName = prefix + key; pathtype = this.$__schema.pathType(pathName); const valForKey = path[key]; // On initial set, delete any nested keys if we're going to overwrite // them to ensure we keep the user's key order. if (type === true && !prefix && valForKey != null && pathtype === 'nested' && this._doc[key] != null) { delete this._doc[key]; // Make sure we set `{}` back even if we minimize re: gh-8565 options = Object.assign({}, options, { _skipMinimizeTopLevel: true }); } else { // Make sure we set `{_skipMinimizeTopLevel: false}` if don't have overwrite: gh-10441 options = Object.assign({}, options, { _skipMinimizeTopLevel: false }); } if (utils.isNonBuiltinObject(valForKey) && pathtype === 'nested') { this.$set(prefix + key, path[key], constructing, Object.assign({}, options, { _skipMarkModified: true })); $applyDefaultsToNested(this.$get(prefix + key), prefix + key, this); continue; } else if (strict) { // Don't overwrite defaults with undefined keys (gh-3981) (gh-9039) if (constructing && path[key] === void 0 && this.$get(pathName) !== void 0) { continue; } if (pathtype === 'adhocOrUndefined') { pathtype = getEmbeddedDiscriminatorPath(this, pathName, { typeOnly: true }); } if (pathtype === 'real' || pathtype === 'virtual') { const p = path[key]; this.$set(prefix + key, p, constructing, options); } else if (pathtype === 'nested' && path[key] instanceof Document) { this.$set(prefix + key, path[key].toObject({ transform: false }), constructing, options); } else if (strict === 'throw') { if (pathtype === 'nested') { throw new ObjectExpectedError(key, path[key]); } else { throw new StrictModeError(key); } } } else if (path[key] !== void 0) { this.$set(prefix + key, path[key], constructing, options); } } // Ensure all properties are in correct order const orderedDoc = {}; const orderedKeys = Object.keys(this.$__schema.tree); for (let i = 0, len = orderedKeys.length; i < len; ++i) { (key = orderedKeys[i]) && (this._doc.hasOwnProperty(key)) && (orderedDoc[key] = undefined); } this._doc = Object.assign(orderedDoc, this._doc); return this; } let pathType = this.$__schema.pathType(path); if (pathType === 'adhocOrUndefined') { pathType = getEmbeddedDiscriminatorPath(this, path, { typeOnly: true }); } // Assume this is a Mongoose document that was copied into a POJO using // `Object.assign()` or `{...doc}` val = handleSpreadDoc(val); // if this doc is being constructed we should not trigger getters const priorVal = (() => { if (this.$__.priorDoc != null) { return this.$__.priorDoc.$__getValue(path); } if (constructing) { return void 0; } return this.$__getValue(path); })(); if (pathType === 'nested' && val) { if (typeof val === 'object' && val != null) { if (val.$__ != null) { val = val.toObject(internalToObjectOptions); } if (val == null) { this.invalidate(path, new MongooseError.CastError('Object', val, path)); return this; } const hasInitialVal = this.$__.savedState != null && this.$__.savedState.hasOwnProperty(path); if (this.$__.savedState != null && !this.$isNew && !this.$__.savedState.hasOwnProperty(path)) { const initialVal = this.$__getValue(path); this.$__.savedState[path] = initialVal; const keys = Object.keys(initialVal || {}); for (const key of keys) { this.$__.savedState[path + '.' + key] = initialVal[key]; } } if (!merge) { this.$__setValue(path, null); cleanModifiedSubpaths(this, path); } else { return this.$set(val, path, constructing); } const keys = getKeysInSchemaOrder(this.$__schema, val, path); this.$__setValue(path, {}); for (const key of keys) { this.$set(path + '.' + key, val[key], constructing, options); } if (priorVal != null && utils.deepEqual(hasInitialVal ? this.$__.savedState[path] : priorVal, val)) { this.unmarkModified(path); } else { this.markModified(path); } return this; } this.invalidate(path, new MongooseError.CastError('Object', val, path)); return this; } let schema; const parts = path.indexOf('.') === -1 ? [path] : path.split('.'); // Might need to change path for top-level alias if (typeof this.$__schema.aliases[parts[0]] === 'string') { parts[0] = this.$__schema.aliases[parts[0]]; } if (pathType === 'adhocOrUndefined' && strict) { // check for roots that are Mixed types let mixed; for (i = 0; i < parts.length; ++i) { const subpath = parts.slice(0, i + 1).join('.'); // If path is underneath a virtual, bypass everything and just set it. if (i + 1 < parts.length && this.$__schema.pathType(subpath) === 'virtual') { mpath.set(path, val, this); return this; } schema = this.$__schema.path(subpath); if (schema == null) { continue; } if (schema instanceof MixedSchema) { // allow changes to sub paths of mixed types mixed = true; break; } } if (schema == null) { // Check for embedded discriminators schema = getEmbeddedDiscriminatorPath(this, path); } if (!mixed && !schema) { if (strict === 'throw') { throw new StrictModeError(path); } return this; } } else if (pathType === 'virtual') { schema = this.$__schema.virtualpath(path); schema.applySetters(val, this); return this; } else { schema = this.$__path(path); } // gh-4578, if setting a deeply nested path that doesn't exist yet, create it let cur = this._doc; let curPath = ''; for (i = 0; i < parts.length - 1; ++i) { cur = cur[parts[i]]; curPath += (curPath.length !== 0 ? '.' : '') + parts[i]; if (!cur) { this.$set(curPath, {}); // Hack re: gh-5800. If nested field is not selected, it probably exists // so `MongoServerError: cannot use the part (nested of nested.num) to // traverse the element ({nested: null})` is not likely. If user gets // that error, its their fault for now. We should reconsider disallowing // modifying not selected paths for 6.x if (!this.$__isSelected(curPath)) { this.unmarkModified(curPath); } cur = this.$__getValue(curPath); } } let pathToMark; // When using the $set operator the path to the field must already exist. // Else mongodb throws: "LEFT_SUBFIELD only supports Object" if (parts.length <= 1) { pathToMark = path; } else { const len = parts.length; for (i = 0; i < len; ++i) { const subpath = parts.slice(0, i + 1).join('.'); if (this.$get(subpath, null, { getters: false }) === null) { pathToMark = subpath; break; } } if (!pathToMark) { pathToMark = path; } } if (!schema) { this.$__set(pathToMark, path, options, constructing, parts, schema, val, priorVal); if (pathType === 'nested' && val == null) { cleanModifiedSubpaths(this, path); } return this; } // If overwriting a subdocument path, make sure to clear out // any errors _before_ setting, so new errors that happen // get persisted. Re: #9080 if (schema.$isSingleNested || schema.$isMongooseArray) { _markValidSubpaths(this, path); } if (val != null && merge && schema.$isSingleNested) { if (val instanceof Document) { val = val.toObject({ virtuals: false, transform: false }); } const keys = Object.keys(val); for (const key of keys) { this.$set(path + '.' + key, val[key], constructing, options); } return this; } let shouldSet = true; try { // If the user is trying to set a ref path to a document with // the correct model name, treat it as populated const refMatches = (() => { if (schema.options == null) { return false; } if (!(val instanceof Document)) { return false; } const model = val.constructor; // Check ref const ref = schema.options.ref; if (ref != null && (ref === model.modelName || ref === model.baseModelName)) { return true; } // Check refPath const refPath = schema.options.refPath; if (refPath == null) { return false; } const modelName = val.get(refPath); return modelName === model.modelName || modelName === model.baseModelName; })(); let didPopulate = false; if (refMatches && val instanceof Document && (!val.$__.wasPopulated || utils.deepEqual(val.$__.wasPopulated.value, val._id))) { const unpopulatedValue = (schema && schema.$isSingleNested) ? schema.cast(val, this) : val._id; this.$populated(path, unpopulatedValue, { [populateModelSymbol]: val.constructor }); val.$__.wasPopulated = { value: unpopulatedValue }; didPopulate = true; } let popOpts; const typeKey = this.$__schema.options.typeKey; if (schema.options && Array.isArray(schema.options[typeKey]) && schema.options[typeKey].length && schema.options[typeKey][0].ref && _isManuallyPopulatedArray(val, schema.options[typeKey][0].ref)) { popOpts = { [populateModelSymbol]: val[0].constructor }; this.$populated(path, val.map(function(v) { return v._id; }), popOpts); for (const doc of val) { doc.$__.wasPopulated = { value: doc._id }; } didPopulate = true; } if (this.$__schema.singleNestedPaths[path] == null && (!refMatches || !schema.$isSingleNested || !val.$__)) { // If this path is underneath a single nested schema, we'll call the setter // later in `$__set()` because we don't take `_doc` when we iterate through // a single nested doc. That's to make sure we get the correct context. // Otherwise we would double-call the setter, see gh-7196. if (options != null && options.overwriteImmutable) { val = schema.applySetters(val, this, false, priorVal, { overwriteImmutable: true }); } else { val = schema.applySetters(val, this, false, priorVal); } } if (Array.isArray(val) && !Array.isArray(schema) && schema.$isMongooseDocumentArray && val.length !== 0 && val[0] != null && val[0].$__ != null && val[0].$__.populated != null) { const populatedPaths = Object.keys(val[0].$__.populated); for (const populatedPath of populatedPaths) { this.$populated(path + '.' + populatedPath, val.map(v => v.$populated(populatedPath)), val[0].$__.populated[populatedPath].options); } didPopulate = true; } if (!didPopulate && this.$__.populated) { // If this array partially contains populated documents, convert them // all to ObjectIds re: #8443 if (Array.isArray(val) && this.$__.populated[path]) { for (let i = 0; i < val.length; ++i) { if (val[i] instanceof Document) { val.set(i, val[i]._id, true); } } } delete this.$__.populated[path]; } if (val != null && schema.$isSingleNested) { _checkImmutableSubpaths(val, schema, priorVal); } this.$markValid(path); } catch (e) { if (e instanceof MongooseError.StrictModeError && e.isImmutableError) { this.invalidate(path, e); } else if (e instanceof MongooseError.CastError) { this.invalidate(e.path, e); if (e.$originalErrorPath) { this.invalidate(path, new MongooseError.CastError(schema.instance, val, path, e.$originalErrorPath)); } } else { this.invalidate(path, new MongooseError.CastError(schema.instance, val, path, e)); } shouldSet = false; } if (shouldSet) { let savedState = null; let savedStatePath = null; if (!constructing) { const doc = this.$isSubdocument ? this.ownerDocument() : this; savedState = doc.$__.savedState; savedStatePath = this.$isSubdocument ? this.$__.fullPath + '.' + path : path; doc.$__saveInitialState(savedStatePath); } this.$__set(pathToMark, path, options, constructing, parts, schema, val, priorVal); if (savedState != null && savedState.hasOwnProperty(savedStatePath) && utils.deepEqual(val, savedState[savedStatePath])) { this.unmarkModified(path); } } if (schema.$isSingleNested && (this.isDirectModified(path) || val == null)) { cleanModifiedSubpaths(this, path); } return this;};
/*! * ignore */function _isManuallyPopulatedArray(val, ref) { if (!Array.isArray(val)) { return false; } if (val.length === 0) { return false; } for (const el of val) { if (!(el instanceof Document)) { return false; } const modelName = el.constructor.modelName; if (modelName == null) { return false; } if (el.constructor.modelName != ref && el.constructor.baseModelName != ref) { return false; } } return true;}
/** * Sets the value of a path, or many paths. * Alias for [`.$set`](#document_Document-$set). * * #### Example: * * // path, value * doc.set(path, value) * * // object * doc.set({ * path : value * , path2 : { * path : value * } * }) * * // on-the-fly cast to number * doc.set(path, value, Number) * * // on-the-fly cast to string * doc.set(path, value, String) * * // changing strict mode behavior * doc.set(path, value, { strict: false }); * * @param {String|Object} path path or object of key/vals to set * @param {Any} val the value to set * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes * @param {Object} [options] optionally specify options that modify the behavior of the set * @return {Document} this * @api public * @method set * @memberOf Document * @instance */Document.prototype.set = Document.prototype.$set;
/** * Determine if we should mark this change as modified. * * @param {never} pathToMark UNUSED * @param {String|Symbol} path * @param {Object} options * @param {Any} constructing * @param {never} parts UNUSED * @param {Schema} schema * @param {Any} val * @param {Any} priorVal * @return {Boolean} * @api private * @method $__shouldModify * @memberOf Document * @instance */Document.prototype.$__shouldModify = function(pathToMark, path, options, constructing, parts, schema, val, priorVal) { if (options && options._skipMarkModified) { return false; } if (this.$isNew) { return true; } // Is path already modified? If so, always modify. We may unmark modified later. if (path in this.$__.activePaths.getStatePaths('modify')) { return true; } // Re: the note about gh-7196, `val` is the raw value without casting or // setters if the full path is under a single nested subdoc because we don't // want to double run setters. So don't set it as modified. See gh-7264. if (this.$__schema.singleNestedPaths[path] != null) { return false; } if (val === void 0 && !this.$__isSelected(path)) { // when a path is not selected in a query, its initial // value will be undefined. return true; } if (val === void 0 && path in this.$__.activePaths.getStatePaths('default')) { // we're just unsetting the default value which was never saved return false; } // gh-3992: if setting a populated field to a doc, don't mark modified // if they have the same _id if (this.$populated(path) && val instanceof Document && deepEqual(val._id, priorVal)) { return false; } if (!deepEqual(val, priorVal || utils.getValue(path, this))) { return true; } if (!constructing && val !== null && val !== undefined && path in this.$__.activePaths.getStatePaths('default') && deepEqual(val, schema.getDefault(this, constructing))) { // a path with a default was $unset on the server // and the user is setting it to the same value again return true; } return false;};
/** * Handles the actual setting of the value and marking the path modified if appropriate. * * @param {String} pathToMark * @param {String|Symbol} path * @param {Object} options * @param {Any} constructing * @param {Array} parts * @param {Schema} schema * @param {Any} val * @param {Any} priorVal * @api private * @method $__set * @memberOf Document * @instance */Document.prototype.$__set = function(pathToMark, path, options, constructing, parts, schema, val, priorVal) { Embedded = Embedded || require('./types/ArraySubdocument'); const shouldModify = this.$__shouldModify(pathToMark, path, options, constructing, parts, schema, val, priorVal); if (shouldModify) { if (this.$__.primitiveAtomics && this.$__.primitiveAtomics[path]) { delete this.$__.primitiveAtomics[path]; if (Object.keys(this.$__.primitiveAtomics).length === 0) { delete this.$__.primitiveAtomics; } } this.markModified(pathToMark); // handle directly setting arrays (gh-1126) MongooseArray || (MongooseArray = require('./types/array')); if (val && utils.isMongooseArray(val)) { val._registerAtomic('$set', val); // Update embedded document parent references (gh-5189) if (utils.isMongooseDocumentArray(val)) { val.forEach(function(item) { item && item.__parentArray && (item.__parentArray = val); }); } } } else if (Array.isArray(val) && Array.isArray(priorVal) && utils.isMongooseArray(val) && utils.isMongooseArray(priorVal)) { val[arrayAtomicsSymbol] = priorVal[arrayAtomicsSymbol]; val[arrayAtomicsBackupSymbol] = priorVal[arrayAtomicsBackupSymbol]; if (utils.isMongooseDocumentArray(val)) { val.forEach(doc => { doc.isNew = false; }); } } let obj = this._doc; let i = 0; const l = parts.length; let cur = ''; for (; i < l; i++) { const next = i + 1; const last = next === l; cur += (cur ? '.' + parts[i] : parts[i]); if (specialProperties.has(parts[i])) { return; } if (last) { if (obj instanceof Map) { obj.set(parts[i], val); } else { obj[parts[i]] = val; } } else { if (utils.isPOJO(obj[parts[i]])) { obj = obj[parts[i]]; } else if (obj[parts[i]] && obj[parts[i]] instanceof Embedded) { obj = obj[parts[i]]; } else if (obj[parts[i]] && !Array.isArray(obj[parts[i]]) && obj[parts[i]].$isSingleNested) { obj = obj[parts[i]]; } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) { obj = obj[parts[i]]; } else { obj[parts[i]] = obj[parts[i]] || {}; obj = obj[parts[i]]; } } }};
/** * Gets a raw value from a path (no getters) * * @param {String} path * @return {Any} Returns the value from the given `path`. * @api private */Document.prototype.$__getValue = function(path) { return utils.getValue(path, this._doc);};
/** * Increments the numeric value at `path` by the given `val`. * When you call `save()` on this document, Mongoose will send a * [`$inc`](https://www.mongodb.com/docs/manual/reference/operator/update/inc/) * as opposed to a `$set`. * * #### Example: * * const schema = new Schema({ counter: Number }); * const Test = db.model('Test', schema); * * const doc = await Test.create({ counter: 0 }); * doc.$inc('counter', 2); * await doc.save(); // Sends a `{ $inc: { counter: 2 } }` to MongoDB * doc.counter; // 2 * * doc.counter += 2; * await doc.save(); // Sends a `{ $set: { counter: 2 } }` to MongoDB * * @param {String|Array} path path or paths to update * @param {Number} val increment `path` by this value * @return {Document} this */Document.prototype.$inc = function $inc(path, val) { if (val == null) { val = 1; } if (Array.isArray(path)) { path.forEach((p) => this.$inc(p, val)); return this; } const schemaType = this.$__path(path); if (schemaType == null) { if (this.$__.strictMode === 'throw') { throw new StrictModeError(path); } else if (this.$__.strictMode === true) { return this; } } else if (schemaType.instance !== 'Number') { this.invalidate(path, new MongooseError.CastError(schemaType.instance, val, path)); return this; } try { val = castNumber(val); } catch (err) { this.invalidate(path, new MongooseError.CastError('number', val, path, err)); } const currentValue = this.$__getValue(path) || 0; this.$__.primitiveAtomics = this.$__.primitiveAtomics || {}; this.$__.primitiveAtomics[path] = { $inc: val }; this.markModified(path); this.$__setValue(path, currentValue + val); return this;};
/** * Sets a raw value for a path (no casting, setters, transformations) * * @param {String} path * @param {Object} value * @return {Document} this * @api private */Document.prototype.$__setValue = function(path, val) { utils.setValue(path, val, this._doc); return this;};
/** * Returns the value of a path. * * #### Example: * * // path * doc.get('age') // 47 * * // dynamic casting to a string * doc.get('age', String) // "47" * * @param {String} path * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for on-the-fly attributes * @param {Object} [options] * @param {Boolean} [options.virtuals=false] Apply virtuals before getting this path * @param {Boolean} [options.getters=true] If false, skip applying getters and just get the raw value * @return {Any} * @api public */Document.prototype.get = function(path, type, options) { let adhoc; options = options || {}; if (type) { adhoc = this.$__schema.interpretAsType(path, type, this.$__schema.options); } let schema = this.$__path(path); if (schema == null) { schema = this.$__schema.virtualpath(path); } if (schema instanceof MixedSchema) { const virtual = this.$__schema.virtualpath(path); if (virtual != null) { schema = virtual; } } const pieces = path.indexOf('.') === -1 ? [path] : path.split('.'); let obj = this._doc; if (schema instanceof VirtualType) { return schema.applyGetters(void 0, this); } // Might need to change path for top-level alias if (typeof this.$__schema.aliases[pieces[0]] === 'string') { pieces[0] = this.$__schema.aliases[pieces[0]]; } for (let i = 0, l = pieces.length; i < l; i++) { if (obj && obj._doc) { obj = obj._doc; } if (obj == null) { obj = void 0; } else if (obj instanceof Map) { obj = obj.get(pieces[i], { getters: false }); } else if (i === l - 1) { obj = utils.getValue(pieces[i], obj); } else { obj = obj[pieces[i]]; } } if (adhoc) { obj = adhoc.cast(obj); } if (schema != null && options.getters !== false) { obj = schema.applyGetters(obj, this); } else if (this.$__schema.nested[path] && options.virtuals) { // Might need to apply virtuals if this is a nested path return applyVirtuals(this, utils.clone(obj) || {}, { path: path }); } return obj;};
/*! * ignore */Document.prototype[getSymbol] = Document.prototype.get;Document.prototype.$get = Document.prototype.get;
/** * Returns the schematype for the given `path`. * * @param {String} path * @return {SchemaPath} * @api private * @method $__path * @memberOf Document * @instance */Document.prototype.$__path = function(path) { const adhocs = this.$__.adhocPaths; const adhocType = adhocs && adhocs.hasOwnProperty(path) ? adhocs[path] : null; if (adhocType) { return adhocType; } return this.$__schema.path(path);};
/** * Marks the path as having pending changes to write to the db. * * _Very helpful when using [Mixed](https://mongoosejs.com/docs/schematypes.html#mixed) types._ * * #### Example: * * doc.mixed.type = 'changed'; * doc.markModified('mixed.type'); * doc.save() // changes to mixed.type are now persisted * * @param {String} path the path to mark modified * @param {Document} [scope] the scope to run validators with * @api public */Document.prototype.markModified = function(path, scope) { this.$__saveInitialState(path); this.$__.activePaths.modify(path); if (scope != null && !this.$isSubdocument) { this.$__.pathsToScopes = this.$__pathsToScopes || {}; this.$__.pathsToScopes[path] = scope; }};
/*! * ignore */Document.prototype.$__saveInitialState = function $__saveInitialState(path) { const savedState = this.$__.savedState; const savedStatePath = path; if (savedState != null) { const firstDot = savedStatePath.indexOf('.'); const topLevelPath = firstDot === -1 ? savedStatePath : savedStatePath.slice(0, firstDot); if (!savedState.hasOwnProperty(topLevelPath)) { savedState[topLevelPath] = utils.clone(this.$__getValue(topLevelPath)); } }};
/** * Clears the modified state on the specified path. * * #### Example: * * doc.foo = 'bar'; * doc.unmarkModified('foo'); * doc.save(); // changes to foo will not be persisted * * @param {String} path the path to unmark modified * @api public */Document.prototype.unmarkModified = function(path) { this.$__.activePaths.init(path); if (this.$__.pathsToScopes != null) { delete this.$__.pathsToScopes[path]; }};
/** * Don't run validation on this path or persist changes to this path. * * #### Example: * * doc.foo = null; * doc.$ignore('foo'); * doc.save(); // changes to foo will not be persisted and validators won't be run * * @memberOf Document * @instance * @method $ignore * @param {String} path the path to ignore * @api public */Document.prototype.$ignore = function(path) { this.$__.activePaths.ignore(path);};
/** * Returns the list of paths that have been directly modified. A direct * modified path is a path that you explicitly set, whether via `doc.foo = 'bar'`, * `Object.assign(doc, { foo: 'bar' })`, or `doc.set('foo', 'bar')`. * * A path `a` may be in `modifiedPaths()` but not in `directModifiedPaths()` * because a child of `a` was directly modified. * * #### Example: * * const schema = new Schema({ foo: String, nested: { bar: String } }); * const Model = mongoose.model('Test', schema); * await Model.create({ foo: 'original', nested: { bar: 'original' } }); * * const doc = await Model.findOne(); * doc.nested.bar = 'modified'; * doc.directModifiedPaths(); // ['nested.bar'] * doc.modifiedPaths(); // ['nested', 'nested.bar'] * * @return {String[]} * @api public */Document.prototype.directModifiedPaths = function() { return Object.keys(this.$__.activePaths.getStatePaths('modify'));};
/** * Returns true if the given path is nullish or only contains empty objects. * Useful for determining whether this subdoc will get stripped out by the * [minimize option](/docs/guide.html#minimize). * * #### Example: * * const schema = new Schema({ nested: { foo: String } }); * const Model = mongoose.model('Test', schema); * const doc = new Model({}); * doc.$isEmpty('nested'); // true * doc.nested.$isEmpty(); // true * * doc.nested.foo = 'bar'; * doc.$isEmpty('nested'); // false * doc.nested.$isEmpty(); // false * * @param {String} [path] * @memberOf Document * @instance * @api public * @method $isEmpty * @return {Boolean} */Document.prototype.$isEmpty = function(path) { const isEmptyOptions = { minimize: true, virtuals: false, getters: false, transform: false }; if (arguments.length !== 0) { const v = this.$get(path); if (v == null) { return true; } if (typeof v !== 'object') { return false; } if (utils.isPOJO(v)) { return _isEmpty(v); } return Object.keys(v.toObject(isEmptyOptions)).length === 0; } return Object.keys(this.toObject(isEmptyOptions)).length === 0;};
/*! * ignore */function _isEmpty(v) { if (v == null) { return true; } if (typeof v !== 'object' || Array.isArray(v)) { return false; } for (const key of Object.keys(v)) { if (!_isEmpty(v[key])) { return false; } } return true;}
/** * Returns the list of paths that have been modified. * * @param {Object} [options] * @param {Boolean} [options.includeChildren=false] if true, returns children of modified paths as well. For example, if false, the list of modified paths for `doc.colors = { primary: 'blue' };` will **not** contain `colors.primary`. If true, `modifiedPaths()` will return an array that contains `colors.primary`. * @return {String[]} * @api public */Document.prototype.modifiedPaths = function(options) { options = options || {}; const directModifiedPaths = Object.keys(this.$__.activePaths.getStatePaths('modify')); const result = new Set(); let i = 0; let j = 0; const len = directModifiedPaths.length; for (i = 0; i < len; ++i) { const path = directModifiedPaths[i]; const parts = parentPaths(path); const pLen = parts.length; for (j = 0; j < pLen; ++j) { result.add(parts[j]); } if (!options.includeChildren) { continue; } let ii = 0; let cur = this.$get(path); if (typeof cur === 'object' && cur !== null) { if (cur._doc) { cur = cur._doc; } const len = cur.length; if (Array.isArray(cur)) { for (ii = 0; ii < len; ++ii) { const subPath = path + '.' + ii; if (!result.has(subPath)) { result.add(subPath); if (cur[ii] != null && cur[ii].$__) { const modified = cur[ii].modifiedPaths(); let iii = 0; const iiiLen = modified.length; for (iii = 0; iii < iiiLen; ++iii) { result.add(subPath + '.' + modified[iii]); } } } } } else { const keys = Object.keys(cur); let ii = 0; const len = keys.length; for (ii = 0; ii < len; ++ii) { result.add(path + '.' + keys[ii]); } } } } return Array.from(result);};
Document.prototype[documentModifiedPaths] = Document.prototype.modifiedPaths;
/** * Returns true if any of the given paths is modified, else false. If no arguments, returns `true` if any path * in this document is modified. * * If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified. * * #### Example: * * doc.set('documents.0.title', 'changed'); * doc.isModified() // true * doc.isModified('documents') // true * doc.isModified('documents.0.title') // true * doc.isModified('documents otherProp') // true * doc.isDirectModified('documents') // false * * @param {String} [path] optional * @return {Boolean} * @api public */Document.prototype.isModified = function(paths, modifiedPaths) { if (paths) { const directModifiedPaths = Object.keys(this.$__.activePaths.getStatePaths('modify')); if (directModifiedPaths.length === 0) { return false; } if (!Array.isArray(paths)) { paths = paths.indexOf(' ') === -1 ? [paths] : paths.split(' '); } const modified = modifiedPaths || this[documentModifiedPaths](); const isModifiedChild = paths.some(function(path) { return !!~modified.indexOf(path); }); return isModifiedChild || paths.some(function(path) { return directModifiedPaths.some(function(mod) { return mod === path || path.startsWith(mod + '.'); }); }); } return this.$__.activePaths.some('modify');};
/** * Alias of [`.isModified`](#document_Document-isModified) * * @method $isModified * @memberOf Document * @api public */Document.prototype.$isModified = Document.prototype.isModified;
Document.prototype[documentIsModified] = Document.prototype.isModified;
/** * Checks if a path is set to its default. * * #### Example: * * MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} }); * const m = new MyModel(); * m.$isDefault('name'); // true * * @memberOf Document * @instance * @method $isDefault * @param {String} [path] * @return {Boolean} * @api public */Document.prototype.$isDefault = function(path) { if (path == null) { return this.$__.activePaths.some('default'); } if (typeof path === 'string' && path.indexOf(' ') === -1) { return this.$__.activePaths.getStatePaths('default').hasOwnProperty(path); } let paths = path; if (!Array.isArray(paths)) { paths = paths.split(' '); } return paths.some(path => this.$__.activePaths.getStatePaths('default').hasOwnProperty(path));};
/** * Getter/setter, determines whether the document was removed or not. * * #### Example: * * const product = await product.remove(); * product.$isDeleted(); // true * product.remove(); // no-op, doesn't send anything to the db * * product.$isDeleted(false); * product.$isDeleted(); // false * product.remove(); // will execute a remove against the db * * * @param {Boolean} [val] optional, overrides whether mongoose thinks the doc is deleted * @return {Boolean|Document} whether mongoose thinks this doc is deleted. * @method $isDeleted * @memberOf Document * @instance * @api public */Document.prototype.$isDeleted = function(val) { if (arguments.length === 0) { return !!this.$__.isDeleted; } this.$__.isDeleted = !!val; return this;};
/** * Returns true if `path` was directly set and modified, else false. * * #### Example: * * doc.set('documents.0.title', 'changed'); * doc.isDirectModified('documents.0.title') // true * doc.isDirectModified('documents') // false * * @param {String|String[]} [path] * @return {Boolean} * @api public */Document.prototype.isDirectModified = function(path) { if (path == null) { return this.$__.activePaths.some('modify'); } if (typeof path === 'string' && path.indexOf(' ') === -1) { return this.$__.activePaths.getStatePaths('modify').hasOwnProperty(path); } let paths = path; if (!Array.isArray(paths)) { paths = paths.split(' '); } return paths.some(path => this.$__.activePaths.getStatePaths('modify').hasOwnProperty(path));};
/** * Checks if `path` is in the `init` state, that is, it was set by `Document#init()` and not modified since. * * @param {String} [path] * @return {Boolean} * @api public */Document.prototype.isInit = function(path) { if (path == null) { return this.$__.activePaths.some('init'); } if (typeof path === 'string' && path.indexOf(' ') === -1) { return this.$__.activePaths.getStatePaths('init').hasOwnProperty(path); } let paths = path; if (!Array.isArray(paths)) { paths = paths.split(' '); } return paths.some(path => this.$__.activePaths.getStatePaths('init').hasOwnProperty(path));};
/** * Checks if `path` was selected in the source query which initialized this document. * * #### Example: * * const doc = await Thing.findOne().select('name'); * doc.isSelected('name') // true * doc.isSelected('age') // false * * @param {String|String[]} path * @return {Boolean} * @api public */Document.prototype.isSelected = function isSelected(path) { if (this.$__.selected == null) { return true; } if (!path) { return false; } if (path === '_id') { return this.$__.selected._id !== 0; } if (path.indexOf(' ') !== -1) { path = path.split(' '); } if (Array.isArray(path)) { return path.some(p => this.$__isSelected(p)); } const paths = Object.keys(this.$__.selected); let inclusive = null; if (paths.length === 1 && paths[0] === '_id') { // only _id was selected. return this.$__.selected._id === 0; } for (const cur of paths) { if (cur === '_id') { continue; } if (!isDefiningProjection(this.$__.selected[cur])) { continue; } inclusive = !!this.$__.selected[cur]; break; } if (inclusive === null) { return true; } if (path in this.$__.selected) { return inclusive; } const pathDot = path + '.'; for (const cur of paths) { if (cur === '_id') { continue; } if (cur.startsWith(pathDot)) { return inclusive || cur !== pathDot; } if (pathDot.startsWith(cur + '.')) { return inclusive; } } return !inclusive;};
Document.prototype.$__isSelected = Document.prototype.isSelected;
/** * Checks if `path` was explicitly selected. If no projection, always returns * true. * * #### Example: * * Thing.findOne().select('nested.name').exec(function (err, doc) { * doc.isDirectSelected('nested.name') // true * doc.isDirectSelected('nested.otherName') // false * doc.isDirectSelected('nested') // false * }) * * @param {String} path * @return {Boolean} * @api public */Document.prototype.isDirectSelected = function isDirectSelected(path) { if (this.$__.selected == null) { return true; } if (path === '_id') { return this.$__.selected._id !== 0; } if (path.indexOf(' ') !== -1) { path = path.split(' '); } if (Array.isArray(path)) { return path.some(p => this.isDirectSelected(p)); } const paths = Object.keys(this.$__.selected); let inclusive = null; if (paths.length === 1 && paths[0] === '_id') { // only _id was selected. return this.$__.selected._id === 0; } for (const cur of paths) { if (cur === '_id') { continue; } if (!isDefiningProjection(this.$__.selected[cur])) { continue; } inclusive = !!this.$__.selected[cur]; break; } if (inclusive === null) { return true; } if (this.$__.selected.hasOwnProperty(path)) { return inclusive; } return !inclusive;};
/** * Executes registered validation rules for this document. * * #### Note: * * This method is called `pre` save and if a validation rule is violated, [save](#model_Model-save) is aborted and the error is returned to your `callback`. * * #### Example: * * doc.validate(function (err) { * if (err) handleError(err); * else // validation passed * }); * * @param {Array|String} [pathsToValidate] list of paths to validate. If set, Mongoose will validate only the modified paths that are in the given list. * @param {Object} [options] internal options * @param {Boolean} [options.validateModifiedOnly=false] if `true` mongoose validates only modified paths. * @param {Array|string} [options.pathsToSkip] list of paths to skip. If set, Mongoose will validate every modified path that is not in this list. * @param {Function} [callback] optional callback called after validation completes, passing an error if one occurred * @return {Promise} Returns a Promise if no `callback` is given. * @api public */Document.prototype.validate = function(pathsToValidate, options, callback) { let parallelValidate; this.$op = 'validate'; if (this.$isSubdocument != null) { // Skip parallel validate check for subdocuments } else if (this.$__.validating) { parallelValidate = new ParallelValidateError(this, { parentStack: options && options.parentStack, conflictStack: this.$__.validating.stack }); } else { this.$__.validating = new ParallelValidateError(this, { parentStack: options && options.parentStack }); } if (arguments.length === 1) { if (typeof arguments[0] === 'object' && !Array.isArray(arguments[0])) { options = arguments[0]; callback = null; pathsToValidate = null; } else if (typeof arguments[0] === 'function') { callback = arguments[0]; options = null; pathsToValidate = null; } } else if (typeof pathsToValidate === 'function') { callback = pathsToValidate; options = null; pathsToValidate = null; } else if (typeof options === 'function') { callback = options; options = pathsToValidate; pathsToValidate = null; } if (options && typeof options.pathsToSkip === 'string') { const isOnePathOnly = options.pathsToSkip.indexOf(' ') === -1; options.pathsToSkip = isOnePathOnly ? [options.pathsToSkip] : options.pathsToSkip.split(' '); } return promiseOrCallback(callback, cb => { if (parallelValidate != null) { return cb(parallelValidate); } this.$__validate(pathsToValidate, options, (error) => { this.$op = null; this.$__.validating = null; cb(error); }); }, this.constructor.events);};
/** * Alias of [`.validate`](#document_Document-validate) * * @method $validate * @memberOf Document * @api public */Document.prototype.$validate = Document.prototype.validate;
/*! * ignore */function _evaluateRequiredFunctions(doc) { const requiredFields = Object.keys(doc.$__.activePaths.getStatePaths('require')); let i = 0; const len = requiredFields.length; for (i = 0; i < len; ++i) { const path = requiredFields[i]; const p = doc.$__schema.path(path); if (p != null && typeof p.originalRequiredValue === 'function') { doc.$__.cachedRequired = doc.$__.cachedRequired || {}; try { doc.$__.cachedRequired[path] = p.originalRequiredValue.call(doc, doc); } catch (err) { doc.invalidate(path, err); } } }}
/*! * ignore */function _getPathsToValidate(doc) { const skipSchemaValidators = {}; _evaluateRequiredFunctions(doc); // only validate required fields when necessary let paths = new Set(Object.keys(doc.$__.activePaths.getStatePaths('require')).filter(function(path) { if (!doc.$__isSelected(path) && !doc.$isModified(path)) { return false; } if (doc.$__.cachedRequired != null && path in doc.$__.cachedRequired) { return doc.$__.cachedRequired[path]; } return true; })); Object.keys(doc.$__.activePaths.getStatePaths('init')).forEach(addToPaths); Object.keys(doc.$__.activePaths.getStatePaths('modify')).forEach(addToPaths); Object.keys(doc.$__.activePaths.getStatePaths('default')).forEach(addToPaths); function addToPaths(p) { paths.add(p); } const subdocs = doc.$getAllSubdocs(); const modifiedPaths = doc.modifiedPaths(); for (const subdoc of subdocs) { if (subdoc.$basePath) { // Remove child paths for now, because we'll be validating the whole // subdoc const fullPathToSubdoc = subdoc.$__fullPathWithIndexes(); for (const p of paths) { if (p == null || p.startsWith(fullPathToSubdoc + '.')) { paths.delete(p); } } if (doc.$isModified(fullPathToSubdoc, modifiedPaths) && !doc.isDirectModified(fullPathToSubdoc) && !doc.$isDefault(fullPathToSubdoc)) { paths.add(fullPathToSubdoc); skipSchemaValidators[fullPathToSubdoc] = true; } } } for (const path of paths) { const _pathType = doc.$__schema.path(path); if (!_pathType) { continue; } if (_pathType.$isMongooseDocumentArray) { for (const p of paths) { if (p == null || p.startsWith(_pathType.path + '.')) { paths.delete(p); } } } // Optimization: if primitive path with no validators, or array of primitives // with no validators, skip validating this path entirely. if (!_pathType.caster && _pathType.validators.length === 0) { paths.delete(path); } else if (_pathType.$isMongooseArray && !_pathType.$isMongooseDocumentArray && // Skip document arrays... !_pathType.$embeddedSchemaType.$isMongooseArray && // and arrays of arrays _pathType.validators.length === 0 && // and arrays with top-level validators _pathType.$embeddedSchemaType.validators.length === 0) { paths.delete(path); } } // from here on we're not removing items from paths // gh-661: if a whole array is modified, make sure to run validation on all // the children as well for (const path of paths) { const _pathType = doc.$__schema.path(path); if (!_pathType) { continue; } if (!_pathType.$isMongooseArray || // To avoid potential performance issues, skip doc arrays whose children // are not required. `getPositionalPathType()` may be slow, so avoid // it unless we have a case of #6364 (!Array.isArray(_pathType) && _pathType.$isMongooseDocumentArray && !(_pathType && _pathType.schemaOptions && _pathType.schemaOptions.required))) { continue; } // gh-11380: optimization. If the array isn't a document array and there's no validators // on the array type, there's no need to run validation on the individual array elements. if (_pathType.$isMongooseArray && !_pathType.$isMongooseDocumentArray && // Skip document arrays... !_pathType.$embeddedSchemaType.$isMongooseArray && // and arrays of arrays _pathType.$embeddedSchemaType.validators.length === 0) { continue; } const val = doc.$__getValue(path); _pushNestedArrayPaths(val, paths, path); } function _pushNestedArrayPaths(val, paths, path) { if (val != null) { const numElements = val.length; for (let j = 0; j < numElements; ++j) { if (Array.isArray(val[j])) { _pushNestedArrayPaths(val[j], paths, path + '.' + j); } else { paths.add(path + '.' + j); } } } } const flattenOptions = { skipArrays: true }; for (const pathToCheck of paths) { if (doc.$__schema.nested[pathToCheck]) { let _v = doc.$__getValue(pathToCheck); if (isMongooseObject(_v)) { _v = _v.toObject({ transform: false }); } const flat = flatten(_v, pathToCheck, flattenOptions, doc.$__schema); Object.keys(flat).forEach(addToPaths); } } for (const path of paths) { // Single nested paths (paths embedded under single nested subdocs) will // be validated on their own when we call `validate()` on the subdoc itself. // Re: gh-8468 if (doc.$__schema.singleNestedPaths.hasOwnProperty(path)) { paths.delete(path); continue; } const _pathType = doc.$__schema.path(path); if (!_pathType || !_pathType.$isSchemaMap) { continue; } const val = doc.$__getValue(path); if (val == null) { continue; } for (const key of val.keys()) { paths.add(path + '.' + key); } } paths = Array.from(paths); return [paths, skipSchemaValidators];}
/*! * ignore */Document.prototype.$__validate = function(pathsToValidate, options, callback) { if (typeof pathsToValidate === 'function') { callback = pathsToValidate; options = null; pathsToValidate = null; } else if (typeof options === 'function') { callback = options; options = null; } const hasValidateModifiedOnlyOption = options && (typeof options === 'object') && ('validateModifiedOnly' in options); const pathsToSkip = (options && options.pathsToSkip) || null; let shouldValidateModifiedOnly; if (hasValidateModifiedOnlyOption) { shouldValidateModifiedOnly = !!options.validateModifiedOnly; } else { shouldValidateModifiedOnly = this.$__schema.options.validateModifiedOnly; } const _this = this; const _complete = () => { let validationError = this.$__.validationError; this.$__.validationError = null; this.$__.validating = null; if (shouldValidateModifiedOnly && validationError != null) { // Remove any validation errors that aren't from modified paths const errors = Object.keys(validationError.errors); for (const errPath of errors) { if (!this.$isModified(errPath)) { delete validationError.errors[errPath]; } } if (Object.keys(validationError.errors).length === 0) { validationError = void 0; } } this.$__.cachedRequired = {}; this.$emit('validate', _this); this.constructor.emit('validate', _this); if (validationError) { for (const key in validationError.errors) { // Make sure cast errors persist if (!this[documentArrayParent] && validationError.errors[key] instanceof MongooseError.CastError) { this.invalidate(key, validationError.errors[key]); } } return validationError; } }; // only validate required fields when necessary const pathDetails = _getPathsToValidate(this); let paths = shouldValidateModifiedOnly ? pathDetails[0].filter((path) => this.$isModified(path)) : pathDetails[0]; const skipSchemaValidators = pathDetails[1]; if (typeof pathsToValidate === 'string') { pathsToValidate = pathsToValidate.split(' '); } if (Array.isArray(pathsToValidate)) { paths = _handlePathsToValidate(paths, pathsToValidate); } else if (pathsToSkip) { paths = _handlePathsToSkip(paths, pathsToSkip); } if (paths.length === 0) { return immediate(function() { const error = _complete(); if (error) { return _this.$__schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) { callback(error); }); } callback(null, _this); }); } const validated = {}; let total = 0; for (const path of paths) { validatePath(path); } function validatePath(path) { if (path == null || validated[path]) { return; } validated[path] = true; total++; immediate(function() { const schemaType = _this.$__schema.path(path); if (!schemaType) { return --total || complete(); } // If user marked as invalid or there was a cast error, don't validate if (!_this.$isValid(path)) { --total || complete(); return; } // If setting a path under a mixed path, avoid using the mixed path validator (gh-10141) if (schemaType[schemaMixedSymbol] != null && path !== schemaType.path) { return --total || complete(); } let val = _this.$__getValue(path); // If you `populate()` and get back a null value, required validators // shouldn't fail (gh-8018). We should always fall back to the populated // value. let pop; if ((pop = _this.$populated(path))) { val = pop; } else if (val != null && val.$__ != null && val.$__.wasPopulated) { // Array paths, like `somearray.1`, do not show up as populated with `$populated()`, // so in that case pull out the document's id val = val._id; } const scope = _this.$__.pathsToScopes != null && path in _this.$__.pathsToScopes ? _this.$__.pathsToScopes[path] : _this; const doValidateOptions = { skipSchemaValidators: skipSchemaValidators[path], path: path, validateModifiedOnly: shouldValidateModifiedOnly }; schemaType.doValidate(val, function(err) { if (err) { const isSubdoc = schemaType.$isSingleNested || schemaType.$isArraySubdocument || schemaType.$isMongooseDocumentArray; if (isSubdoc && err instanceof ValidationError) { return --total || complete(); } _this.invalidate(path, err, undefined, true); } --total || complete(); }, scope, doValidateOptions); }); } function complete() { const error = _complete(); if (error) { return _this.$__schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) { callback(error); }); } callback(null, _this); }};
/*! * ignore */function _handlePathsToValidate(paths, pathsToValidate) { const _pathsToValidate = new Set(pathsToValidate); const parentPaths = new Map([]); for (const path of pathsToValidate) { if (path.indexOf('.') === -1) { continue; } const pieces = path.split('.'); let cur = pieces[0]; for (let i = 1; i < pieces.length; ++i) { // Since we skip subpaths under single nested subdocs to // avoid double validation, we need to add back the // single nested subpath if the user asked for it (gh-8626) parentPaths.set(cur, path); cur = cur + '.' + pieces[i]; } } const ret = []; for (const path of paths) { if (_pathsToValidate.has(path)) { ret.push(path); } else if (parentPaths.has(path)) { ret.push(parentPaths.get(path)); } } return ret;}
/*! * ignore */function _handlePathsToSkip(paths, pathsToSkip) { pathsToSkip = new Set(pathsToSkip); paths = paths.filter(p => !pathsToSkip.has(p)); return paths;}
/** * Executes registered validation rules (skipping asynchronous validators) for this document. * * #### Note: * * This method is useful if you need synchronous validation. * * #### Example: * * const err = doc.validateSync(); * if (err) { * handleError(err); * } else { * // validation passed * } * * @param {Array|string} [pathsToValidate] only validate the given paths * @param {Object} [options] options for validation * @param {Boolean} [options.validateModifiedOnly=false] If `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths. * @param {Array|string} [options.pathsToSkip] list of paths to skip. If set, Mongoose will validate every modified path that is not in this list. * @return {ValidationError|undefined} ValidationError if there are errors during validation, or undefined if there is no error. * @api public */Document.prototype.validateSync = function(pathsToValidate, options) { const _this = this; if (arguments.length === 1 && typeof arguments[0] === 'object' && !Array.isArray(arguments[0])) { options = arguments[0]; pathsToValidate = null; } const hasValidateModifiedOnlyOption = options && (typeof options === 'object') && ('validateModifiedOnly' in options); let shouldValidateModifiedOnly; if (hasValidateModifiedOnlyOption) { shouldValidateModifiedOnly = !!options.validateModifiedOnly; } else { shouldValidateModifiedOnly = this.$__schema.options.validateModifiedOnly; } let pathsToSkip = options && options.pathsToSkip; if (typeof pathsToValidate === 'string') { const isOnePathOnly = pathsToValidate.indexOf(' ') === -1; pathsToValidate = isOnePathOnly ? [pathsToValidate] : pathsToValidate.split(' '); } else if (typeof pathsToSkip === 'string' && pathsToSkip.indexOf(' ') !== -1) { pathsToSkip = pathsToSkip.split(' '); } // only validate required fields when necessary const pathDetails = _getPathsToValidate(this); let paths = shouldValidateModifiedOnly ? pathDetails[0].filter((path) => this.$isModified(path)) : pathDetails[0]; const skipSchemaValidators = pathDetails[1]; if (Array.isArray(pathsToValidate)) { paths = _handlePathsToValidate(paths, pathsToValidate); } else if (Array.isArray(pathsToSkip)) { paths = _handlePathsToSkip(paths, pathsToSkip); } const validating = {}; for (let i = 0, len = paths.length; i < len; ++i) { const path = paths[i]; if (validating[path]) { continue; } validating[path] = true; const p = _this.$__schema.path(path); if (!p) { continue; } if (!_this.$isValid(path)) { continue; } const val = _this.$__getValue(path); const err = p.doValidateSync(val, _this, { skipSchemaValidators: skipSchemaValidators[path], path: path, validateModifiedOnly: shouldValidateModifiedOnly }); if (err) { const isSubdoc = p.$isSingleNested || p.$isArraySubdocument || p.$isMongooseDocumentArray; if (isSubdoc && err instanceof ValidationError) { continue; } _this.invalidate(path, err, undefined, true); } } const err = _this.$__.validationError; _this.$__.validationError = undefined; _this.$emit('validate', _this); _this.constructor.emit('validate', _this); if (err) { for (const key in err.errors) { // Make sure cast errors persist if (err.errors[key] instanceof MongooseError.CastError) { _this.invalidate(key, err.errors[key]); } } } return err;};
/** * Marks a path as invalid, causing validation to fail. * * The `errorMsg` argument will become the message of the `ValidationError`. * * The `value` argument (if passed) will be available through the `ValidationError.value` property. * * doc.invalidate('size', 'must be less than 20', 14); * * doc.validate(function (err) { * console.log(err) * // prints * { message: 'Validation failed', * name: 'ValidationError', * errors: * { size: * { message: 'must be less than 20', * name: 'ValidatorError', * path: 'size', * type: 'user defined', * value: 14 } } } * }) * * @param {String} path the field to invalidate. For array elements, use the `array.i.field` syntax, where `i` is the 0-based index in the array. * @param {String|Error} err the error which states the reason `path` was invalid * @param {Object|String|Number|any} val optional invalid value * @param {String} [kind] optional `kind` property for the error * @return {ValidationError} the current ValidationError, with all currently invalidated paths * @api public */Document.prototype.invalidate = function(path, err, val, kind) { if (!this.$__.validationError) { this.$__.validationError = new ValidationError(this); } if (this.$__.validationError.errors[path]) { return; } if (!err || typeof err === 'string') { err = new ValidatorError({ path: path, message: err, type: kind || 'user defined', value: val }); } if (this.$__.validationError === err) { return this.$__.validationError; } this.$__.validationError.addError(path, err); return this.$__.validationError;};
/** * Marks a path as valid, removing existing validation errors. * * @param {String} path the field to mark as valid * @api public * @memberOf Document * @instance * @method $markValid */Document.prototype.$markValid = function(path) { if (!this.$__.validationError || !this.$__.validationError.errors[path]) { return; } delete this.$__.validationError.errors[path]; if (Object.keys(this.$__.validationError.errors).length === 0) { this.$__.validationError = null; }};
/*! * ignore */function _markValidSubpaths(doc, path) { if (!doc.$__.validationError) { return; } const keys = Object.keys(doc.$__.validationError.errors); for (const key of keys) { if (key.startsWith(path + '.')) { delete doc.$__.validationError.errors[key]; } } if (Object.keys(doc.$__.validationError.errors).length === 0) { doc.$__.validationError = null; }}
/*! * ignore */function _checkImmutableSubpaths(subdoc, schematype, priorVal) { const schema = schematype.schema; if (schema == null) { return; } for (const key of Object.keys(schema.paths)) { const path = schema.paths[key]; if (path.$immutableSetter == null) { continue; } const oldVal = priorVal == null ? void 0 : priorVal.$__getValue(key); // Calling immutableSetter with `oldVal` even though it expects `newVal` // is intentional. That's because `$immutableSetter` compares its param // to the current value. path.$immutableSetter.call(subdoc, oldVal); }}
/** * Saves this document by inserting a new document into the database if [document.isNew](/docs/api.html#document_Document-isNew) is `true`, * or sends an [updateOne](/docs/api.html#document_Document-updateOne) operation **only** with the modifications to the database, it does not replace the whole document in the latter case. * * #### Example: * * product.sold = Date.now(); * product = await product.save(); * * If save is successful, the returned promise will fulfill with the document * saved. * * #### Example: * * const newProduct = await product.save(); * newProduct === product; // true * * @param {Object} [options] options optional options * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](https://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead. * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. * @param {Boolean} [options.validateModifiedOnly=false] If `true`, Mongoose will only validate modified paths, as opposed to modified paths and `required` paths. * @param {Number|String} [options.w] set the [write concern](https://docs.mongodb.com/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) * @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) * @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern). * @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names) * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`. * @param {Function} [fn] optional callback * @method save * @memberOf Document * @instance * @throws {DocumentNotFoundError} if this [save updates an existing document](api.html#document_Document-isNew) but the document doesn't exist in the database. For example, you will get this error if the document is [deleted between when you retrieved the document and when you saved it](documents.html#updating). * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise. * @api public * @see middleware https://mongoosejs.com/docs/middleware.html *//** * Checks if a path is invalid * * @param {String|String[]} [path] the field to check. If unset will always return "false" * @method $isValid * @memberOf Document * @instance * @api private */Document.prototype.$isValid = function(path) { if (this.$__.validationError == null || Object.keys(this.$__.validationError.errors).length === 0) { return true; } if (path == null) { return false; } if (path.indexOf(' ') !== -1) { path = path.split(' '); } if (Array.isArray(path)) { return path.some(p => this.$__.validationError.errors[p] == null); } return this.$__.validationError.errors[path] == null;};
/** * Resets the internal modified state of this document. * * @api private * @return {Document} this * @method $__reset * @memberOf Document * @instance */Document.prototype.$__reset = function reset() { let _this = this; // Skip for subdocuments const subdocs = this.$parent() === this ? this.$getAllSubdocs() : []; const resetArrays = new Set(); for (const subdoc of subdocs) { const fullPathWithIndexes = subdoc.$__fullPathWithIndexes(); if (this.isModified(fullPathWithIndexes) || isParentInit(fullPathWithIndexes)) { subdoc.$__reset(); if (subdoc.$isDocumentArrayElement) { if (!resetArrays.has(subdoc.parentArray())) { const array = subdoc.parentArray(); this.$__.activePaths.clearPath(fullPathWithIndexes.replace(/\.\d+$/, '').slice(-subdoc.$basePath - 1)); array[arrayAtomicsBackupSymbol] = array[arrayAtomicsSymbol]; array[arrayAtomicsSymbol] = {}; resetArrays.add(array); } } else { if (subdoc.$parent() === this) { this.$__.activePaths.clearPath(subdoc.$basePath); } else if (subdoc.$parent() != null && subdoc.$parent().$isSubdocument) { // If map path underneath subdocument, may end up with a case where // map path is modified but parent still needs to be reset. See gh-10295 subdoc.$parent().$__reset(); } } } } function isParentInit(path) { path = path.indexOf('.') === -1 ? [path] : path.split('.'); let cur = ''; for (let i = 0; i < path.length; ++i) { cur += (cur.length ? '.' : '') + path[i]; if (_this.$__.activePaths[cur] === 'init') { return true; } } return false; } // clear atomics this.$__dirty().forEach(function(dirt) { const type = dirt.value; if (type && type[arrayAtomicsSymbol]) { type[arrayAtomicsBackupSymbol] = type[arrayAtomicsSymbol]; type[arrayAtomicsSymbol] = {}; } }); this.$__.backup = {}; this.$__.backup.activePaths = { modify: Object.assign({}, this.$__.activePaths.getStatePaths('modify')), default: Object.assign({}, this.$__.activePaths.getStatePaths('default')) }; this.$__.backup.validationError = this.$__.validationError; this.$__.backup.errors = this.$errors; // Clear 'dirty' cache this.$__.activePaths.clear('modify'); this.$__.activePaths.clear('default'); this.$__.validationError = undefined; this.$errors = undefined; _this = this; this.$__schema.requiredPaths().forEach(function(path) { _this.$__.activePaths.require(path); }); return this;};
/*! * ignore */Document.prototype.$__undoReset = function $__undoReset() { if (this.$__.backup == null || this.$__.backup.activePaths == null) { return; } this.$__.activePaths.states.modify = this.$__.backup.activePaths.modify; this.$__.activePaths.states.default = this.$__.backup.activePaths.default; this.$__.validationError = this.$__.backup.validationError; this.$errors = this.$__.backup.errors; for (const dirt of this.$__dirty()) { const type = dirt.value; if (type && type[arrayAtomicsSymbol] && type[arrayAtomicsBackupSymbol]) { type[arrayAtomicsSymbol] = type[arrayAtomicsBackupSymbol]; } } for (const subdoc of this.$getAllSubdocs()) { subdoc.$__undoReset(); }};
/** * Returns this documents dirty paths / vals. * * @return {Array} * @api private * @method $__dirty * @memberOf Document * @instance */Document.prototype.$__dirty = function() { const _this = this; let all = this.$__.activePaths.map('modify', function(path) { return { path: path, value: _this.$__getValue(path), schema: _this.$__path(path) }; }); // gh-2558: if we had to set a default and the value is not undefined, // we have to save as well all = all.concat(this.$__.activePaths.map('default', function(path) { if (path === '_id' || _this.$__getValue(path) == null) { return; } return { path: path, value: _this.$__getValue(path), schema: _this.$__path(path) }; })); const allPaths = new Map(all.filter((el) => el != null).map((el) => [el.path, el.value])); // Ignore "foo.a" if "foo" is dirty already. const minimal = []; all.forEach(function(item) { if (!item) { return; } let top = null; const array = parentPaths(item.path); for (let i = 0; i < array.length - 1; i++) { if (allPaths.has(array[i])) { top = allPaths.get(array[i]); break; } } if (top == null) { minimal.push(item); } else if (top != null && top[arrayAtomicsSymbol] != null && top.hasAtomics()) { // special case for top level MongooseArrays // the `top` array itself and a sub path of `top` are being set. // the only way to honor all of both modifications is through a $set // of entire array. top[arrayAtomicsSymbol] = {}; top[arrayAtomicsSymbol].$set = top; } }); return minimal;};
/** * Assigns/compiles `schema` into this documents prototype. * * @param {Schema} schema * @api private * @method $__setSchema * @memberOf Document * @instance */Document.prototype.$__setSchema = function(schema) { compile(schema.tree, this, undefined, schema.options); // Apply default getters if virtual doesn't have any (gh-6262) for (const key of Object.keys(schema.virtuals)) { schema.virtuals[key]._applyDefaultGetters(); } if (schema.path('schema') == null) { this.schema = schema; } this.$__schema = schema; this[documentSchemaSymbol] = schema;};

/** * Get active path that were changed and are arrays * * @return {Array} * @api private * @method $__getArrayPathsToValidate * @memberOf Document * @instance */Document.prototype.$__getArrayPathsToValidate = function() { DocumentArray || (DocumentArray = require('./types/DocumentArray')); // validate all document arrays. return this.$__.activePaths .map('init', 'modify', function(i) { return this.$__getValue(i); }.bind(this)) .filter(function(val) { return val && Array.isArray(val) && utils.isMongooseDocumentArray(val) && val.length; }).reduce(function(seed, array) { return seed.concat(array); }, []) .filter(function(doc) { return doc; });};

/** * Get all subdocs (by bfs) * * @return {Array} * @api public * @method $getAllSubdocs * @memberOf Document * @instance */Document.prototype.$getAllSubdocs = function() { DocumentArray || (DocumentArray = require('./types/DocumentArray')); Embedded = Embedded || require('./types/ArraySubdocument'); function docReducer(doc, seed, path) { let val = doc; let isNested = false; if (path) { if (doc instanceof Document && doc[documentSchemaSymbol].paths[path]) { val = doc._doc[path]; } else if (doc instanceof Document && doc[documentSchemaSymbol].nested[path]) { val = doc._doc[path]; isNested = true; } else { val = doc[path]; } } if (val instanceof Embedded) { seed.push(val); } else if (val instanceof Map) { seed = Array.from(val.keys()).reduce(function(seed, path) { return docReducer(val.get(path), seed, null); }, seed); } else if (val && !Array.isArray(val) && val.$isSingleNested) { seed = Object.keys(val._doc).reduce(function(seed, path) { return docReducer(val, seed, path); }, seed); seed.push(val); } else if (val && utils.isMongooseDocumentArray(val)) { val.forEach(function _docReduce(doc) { if (!doc || !doc._doc) { return; } seed = Object.keys(doc._doc).reduce(function(seed, path) { return docReducer(doc._doc, seed, path); }, seed); if (doc instanceof Embedded) { seed.push(doc); } }); } else if (isNested && val != null) { for (const path of Object.keys(val)) { docReducer(val, seed, path); } } return seed; } const subDocs = []; for (const path of Object.keys(this._doc)) { docReducer(this, subDocs, path); } return subDocs;};
/*! * Runs queued functions */function applyQueue(doc) { const q = doc.$__schema && doc.$__schema.callQueue; if (!q.length) { return; } for (const pair of q) { if (pair[0] !== 'pre' && pair[0] !== 'post' && pair[0] !== 'on') { doc[pair[0]].apply(doc, pair[1]); } }}
/*! * ignore */Document.prototype.$__handleReject = function handleReject(err) { // emit on the Model if listening if (this.$listeners('error').length) { this.$emit('error', err); } else if (this.constructor.listeners && this.constructor.listeners('error').length) { this.constructor.emit('error', err); }};
/** * Internal helper for toObject() and toJSON() that doesn't manipulate options * * @return {Object} * @api private * @method $toObject * @memberOf Document * @instance */Document.prototype.$toObject = function(options, json) { let defaultOptions = { transform: true, flattenDecimals: true }; const path = json ? 'toJSON' : 'toObject'; const baseOptions = this.constructor && this.constructor.base && this.constructor.base.options && get(this.constructor.base.options, path) || {}; const schemaOptions = this.$__schema && this.$__schema.options || {}; // merge base default options with Schema's set default options if available. // `clone` is necessary here because `utils.options` directly modifies the second input. defaultOptions = utils.options(defaultOptions, clone(baseOptions)); defaultOptions = utils.options(defaultOptions, clone(schemaOptions[path] || {})); // If options do not exist or is not an object, set it to empty object options = utils.isPOJO(options) ? { ...options } : {}; options._calledWithOptions = options._calledWithOptions || { ...options }; let _minimize; if (options._calledWithOptions.minimize != null) { _minimize = options.minimize; } else if (defaultOptions.minimize != null) { _minimize = defaultOptions.minimize; } else { _minimize = schemaOptions.minimize; } let flattenMaps; if (options._calledWithOptions.flattenMaps != null) { flattenMaps = options.flattenMaps; } else if (defaultOptions.flattenMaps != null) { flattenMaps = defaultOptions.flattenMaps; } else { flattenMaps = schemaOptions.flattenMaps; } // The original options that will be passed to `clone()`. Important because // `clone()` will recursively call `$toObject()` on embedded docs, so we // need the original options the user passed in, plus `_isNested` and // `_parentOptions` for checking whether we need to depopulate. const cloneOptions = Object.assign({}, options, { _isNested: true, json: json, minimize: _minimize, flattenMaps: flattenMaps, _seen: (options && options._seen) || new Map() }); if (utils.hasUserDefinedProperty(options, 'getters')) { cloneOptions.getters = options.getters; } if (utils.hasUserDefinedProperty(options, 'virtuals')) { cloneOptions.virtuals = options.virtuals; } const depopulate = options.depopulate || (options._parentOptions && options._parentOptions.depopulate || false); // _isNested will only be true if this is not the top level document, we // should never depopulate the top-level document if (depopulate && options._isNested && this.$__.wasPopulated) { return clone(this.$__.wasPopulated.value || this._id, cloneOptions); } // merge default options with input options. options = utils.options(defaultOptions, options); options._isNested = true; options.json = json; options.minimize = _minimize; cloneOptions._parentOptions = options; cloneOptions._skipSingleNestedGetters = false; const gettersOptions = Object.assign({}, cloneOptions); gettersOptions._skipSingleNestedGetters = true; // remember the root transform function // to save it from being overwritten by sub-transform functions const originalTransform = options.transform; let ret = clone(this._doc, cloneOptions) || {}; if (options.getters) { applyGetters(this, ret, gettersOptions); if (options.minimize) { ret = minimize(ret) || {}; } } if (options.virtuals || (options.getters && options.virtuals !== false)) { applyVirtuals(this, ret, gettersOptions, options); } if (options.versionKey === false && this.$__schema.options.versionKey) { delete ret[this.$__schema.options.versionKey]; } let transform = options.transform; // In the case where a subdocument has its own transform function, we need to // check and see if the parent has a transform (options.transform) and if the // child schema has a transform (this.schema.options.toObject) In this case, // we need to adjust options.transform to be the child schema's transform and // not the parent schema's if (transform) { applySchemaTypeTransforms(this, ret); } if (options.useProjection) { omitDeselectedFields(this, ret); } if (transform === true || (schemaOptions.toObject && transform)) { const opts = options.json ? schemaOptions.toJSON : schemaOptions.toObject; if (opts) { transform = (typeof options.transform === 'function' ? options.transform : opts.transform); } } else { options.transform = originalTransform; } if (typeof transform === 'function') { const xformed = transform(this, ret, options); if (typeof xformed !== 'undefined') { ret = xformed; } } return ret;};
/** * Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). * * Buffers are converted to instances of [mongodb.Binary](https://mongodb.github.io/node-mongodb-native/4.9/classes/Binary.html) for proper storage. * * #### Getters/Virtuals * * Example of only applying path getters * * doc.toObject({ getters: true, virtuals: false }) * * Example of only applying virtual getters * * doc.toObject({ virtuals: true }) * * Example of applying both path and virtual getters * * doc.toObject({ getters: true }) * * To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument. * * schema.set('toObject', { virtuals: true }) * * #### Transform: * * We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional `transform` function. * * Transform functions receive three arguments * * function (doc, ret, options) {} * * - `doc` The mongoose document which is being converted * - `ret` The plain object representation which has been converted * - `options` The options in use (either schema options or the options passed inline) * * #### Example: * * // specify the transform schema option * if (!schema.options.toObject) schema.options.toObject = {}; * schema.options.toObject.transform = function (doc, ret, options) { * // remove the _id of every document before returning the result * delete ret._id; * return ret; * } * * // without the transformation in the schema * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } * * // with the transformation * doc.toObject(); // { name: 'Wreck-it Ralph' } * * With transformations we can do a lot more than remove properties. We can even return completely new customized objects: * * if (!schema.options.toObject) schema.options.toObject = {}; * schema.options.toObject.transform = function (doc, ret, options) { * return { movie: ret.name } * } * * // without the transformation in the schema * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } * * // with the transformation * doc.toObject(); // { movie: 'Wreck-it Ralph' } * * _Note: if a transform function returns `undefined`, the return value will be ignored._ * * Transformations may also be applied inline, overridding any transform set in the options: * * function xform (doc, ret, options) { * return { inline: ret.name, custom: true } * } * * // pass the transform as an inline option * doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true } * * If you want to skip transformations, use `transform: false`: * * schema.options.toObject.hide = '_id'; * schema.options.toObject.transform = function (doc, ret, options) { * if (options.hide) { * options.hide.split(' ').forEach(function (prop) { * delete ret[prop]; * }); * } * return ret; * } * * const doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }); * doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' } * doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' } * doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' } * * If you pass a transform in `toObject()` options, Mongoose will apply the transform * to [subdocuments](/docs/subdocs.html) in addition to the top-level document. * Similarly, `transform: false` skips transforms for all subdocuments. * Note that this behavior is different for transforms defined in the schema: * if you define a transform in `schema.options.toObject.transform`, that transform * will **not** apply to subdocuments. * * const memberSchema = new Schema({ name: String, email: String }); * const groupSchema = new Schema({ members: [memberSchema], name: String, email }); * const Group = mongoose.model('Group', groupSchema); * * const doc = new Group({ * name: 'Engineering', * email: 'dev@mongoosejs.io', * members: [{ name: 'Val', email: 'val@mongoosejs.io' }] * }); * * // Removes `email` from both top-level document **and** array elements * // { name: 'Engineering', members: [{ name: 'Val' }] } * doc.toObject({ transform: (doc, ret) => { delete ret.email; return ret; } }); * * Transforms, like all of these options, are also available for `toJSON`. See [this guide to `JSON.stringify()`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html) to learn why `toJSON()` and `toObject()` are separate functions. * * See [schema options](/docs/guide.html#toObject) for some more details. * * _During save, no custom options are applied to the document before being sent to the database._ * * @param {Object} [options] * @param {Boolean} [options.getters=false] if true, apply all getters, including virtuals * @param {Boolean} [options.virtuals=false] if true, apply virtuals, including aliases. Use `{ getters: true, virtuals: false }` to just apply getters, not virtuals * @param {Boolean} [options.aliases=true] if `options.virtuals = true`, you can set `options.aliases = false` to skip applying aliases. This option is a no-op if `options.virtuals = false`. * @param {Boolean} [options.minimize=true] if true, omit any empty objects from the output * @param {Function|null} [options.transform=null] if set, mongoose will call this function to allow you to transform the returned object * @param {Boolean} [options.depopulate=false] if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths. * @param {Boolean} [options.versionKey=true] if false, exclude the version key (`__v` by default) from the output * @param {Boolean} [options.flattenMaps=false] if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`. * @param {Boolean} [options.useProjection=false] - If true, omits fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema. * @return {Object} js object (not a POJO) * @see mongodb.Binary https://mongodb.github.io/node-mongodb-native/4.9/classes/Binary.html * @api public * @memberOf Document * @instance */Document.prototype.toObject = function(options) { return this.$toObject(options);};
/** * Minimizes an object, removing undefined values and empty objects * * @param {Object} object to minimize * @return {Object} * @api private */function minimize(obj) { const keys = Object.keys(obj); let i = keys.length; let hasKeys; let key; let val; while (i--) { key = keys[i]; val = obj[key]; if (utils.isPOJO(val)) { obj[key] = minimize(val); } if (undefined === obj[key]) { delete obj[key]; continue; } hasKeys = true; } return hasKeys ? obj : undefined;}
/*! * Applies virtuals properties to `json`. */function applyVirtuals(self, json, options, toObjectOptions) { const schema = self.$__schema; const paths = Object.keys(schema.virtuals); let i = paths.length; const numPaths = i; let path; let assignPath; let cur = self._doc; let v; const aliases = typeof (toObjectOptions && toObjectOptions.aliases) === 'boolean' ? toObjectOptions.aliases : true; let virtualsToApply = null; if (Array.isArray(options.virtuals)) { virtualsToApply = new Set(options.virtuals); } else if (options.virtuals && options.virtuals.pathsToSkip) { virtualsToApply = new Set(paths); for (let i = 0; i < options.virtuals.pathsToSkip.length; i++) { if (virtualsToApply.has(options.virtuals.pathsToSkip[i])) { virtualsToApply.delete(options.virtuals.pathsToSkip[i]); } } } if (!cur) { return json; } options = options || {}; for (i = 0; i < numPaths; ++i) { path = paths[i]; if (virtualsToApply != null && !virtualsToApply.has(path)) { continue; } // Allow skipping aliases with `toObject({ virtuals: true, aliases: false })` if (!aliases && schema.aliases.hasOwnProperty(path)) { continue; } // We may be applying virtuals to a nested object, for example if calling // `doc.nestedProp.toJSON()`. If so, the path we assign to, `assignPath`, // will be a trailing substring of the `path`. assignPath = path; if (options.path != null) { if (!path.startsWith(options.path + '.')) { continue; } assignPath = path.substring(options.path.length + 1); } const parts = assignPath.split('.'); v = clone(self.get(path), options); if (v === void 0) { continue; } const plen = parts.length; cur = json; for (let j = 0; j < plen - 1; ++j) { cur[parts[j]] = cur[parts[j]] || {}; cur = cur[parts[j]]; } cur[parts[plen - 1]] = v; } return json;}

/** * Applies virtuals properties to `json`. * * @param {Document} self * @param {Object} json * @param {Object} [options] * @return {Object} `json` * @api private */function applyGetters(self, json, options) { const schema = self.$__schema; const paths = Object.keys(schema.paths); let i = paths.length; let path; let cur = self._doc; let v; if (!cur) { return json; } while (i--) { path = paths[i]; const parts = path.split('.'); const plen = parts.length; const last = plen - 1; let branch = json; let part; cur = self._doc; if (!self.$__isSelected(path)) { continue; } for (let ii = 0; ii < plen; ++ii) { part = parts[ii]; v = cur[part]; if (ii === last) { const val = self.$get(path); branch[part] = clone(val, options); } else if (v == null) { if (part in cur) { branch[part] = v; } break; } else { branch = branch[part] || (branch[part] = {}); } cur = v; } } return json;}
/** * Applies schema type transforms to `json`. * * @param {Document} self * @param {Object} json * @return {Object} `json` * @api private */function applySchemaTypeTransforms(self, json) { const schema = self.$__schema; const paths = Object.keys(schema.paths || {}); const cur = self._doc; if (!cur) { return json; } for (const path of paths) { const schematype = schema.paths[path]; if (typeof schematype.options.transform === 'function') { const val = self.$get(path); if (val === undefined) { continue; } const transformedValue = schematype.options.transform.call(self, val); throwErrorIfPromise(path, transformedValue); utils.setValue(path, transformedValue, json); } else if (schematype.$embeddedSchemaType != null && typeof schematype.$embeddedSchemaType.options.transform === 'function') { const val = self.$get(path); if (val === undefined) { continue; } const vals = [].concat(val); const transform = schematype.$embeddedSchemaType.options.transform; for (let i = 0; i < vals.length; ++i) { const transformedValue = transform.call(self, vals[i]); vals[i] = transformedValue; throwErrorIfPromise(path, transformedValue); } json[path] = vals; } } return json;}
function throwErrorIfPromise(path, transformedValue) { if (isPromise(transformedValue)) { throw new Error('`transform` function must be synchronous, but the transform on path `' + path + '` returned a promise.'); }}
/*! * ignore */function omitDeselectedFields(self, json) { const schema = self.$__schema; const paths = Object.keys(schema.paths || {}); const cur = self._doc; if (!cur) { return json; } let selected = self.$__.selected; if (selected === void 0) { selected = {}; queryhelpers.applyPaths(selected, schema); } if (selected == null || Object.keys(selected).length === 0) { return json; } for (const path of paths) { if (selected[path] != null && !selected[path]) { delete json[path]; } } return json;}
/** * The return value of this method is used in calls to [`JSON.stringify(doc)`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript#the-tojson-function). * * This method accepts the same options as [Document#toObject](#document_Document-toObject). To apply the options to every document of your schema by default, set your [schemas](#schema_Schema) `toJSON` option to the same argument. * * schema.set('toJSON', { virtuals: true }); * * There is one difference between `toJSON()` and `toObject()` options. * When you call `toJSON()`, the [`flattenMaps` option](./document.html#document_Document-toObject) defaults to `true`, because `JSON.stringify()` doesn't convert maps to objects by default. * When you call `toObject()`, the `flattenMaps` option is `false` by default. * * See [schema options](/docs/guide.html#toJSON) for more information on setting `toJSON` option defaults. * * @param {Object} options * @param {Boolean} [options.flattenMaps=true] if true, convert Maps to [POJOs](https://masteringjs.io/tutorials/fundamentals/pojo). Useful if you want to `JSON.stringify()` the result. * @return {Object} * @see Document#toObject #document_Document-toObject * @see JSON.stringify() in JavaScript https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html * @api public * @memberOf Document * @instance */Document.prototype.toJSON = function(options) { return this.$toObject(options, true);};

Document.prototype.ownerDocument = function() { return this;};

/** * If this document is a subdocument or populated document, returns the document's * parent. Returns the original document if there is no parent. * * @return {Document} * @api public * @method parent * @memberOf Document * @instance */Document.prototype.parent = function() { if (this.$isSubdocument || this.$__.wasPopulated) { return this.$__.parent; } return this;};
/** * Alias for [`parent()`](#document_Document-parent). If this document is a subdocument or populated * document, returns the document's parent. Returns `undefined` otherwise. * * @return {Document} * @api public * @method $parent * @memberOf Document * @instance */Document.prototype.$parent = Document.prototype.parent;
/** * Helper for console.log * * @return {String} * @api public * @method inspect * @memberOf Document * @instance */Document.prototype.inspect = function(options) { const isPOJO = utils.isPOJO(options); let opts; if (isPOJO) { opts = options; opts.minimize = false; } const ret = this.toObject(opts); if (ret == null) { // If `toObject()` returns null, `this` is still an object, so if `inspect()` // prints out null this can cause some serious confusion. See gh-7942. return 'MongooseDocument { ' + ret + ' }'; } return ret;};
if (inspect.custom) { // Avoid Node deprecation warning DEP0079 Document.prototype[inspect.custom] = Document.prototype.inspect;}
/** * Helper for console.log * * @return {String} * @api public * @method toString * @memberOf Document * @instance */Document.prototype.toString = function() { const ret = this.inspect(); if (typeof ret === 'string') { return ret; } return inspect(ret);};
/** * Returns true if this document is equal to another document. * * Documents are considered equal when they have matching `_id`s, unless neither * document has an `_id`, in which case this function falls back to using * `deepEqual()`. * * @param {Document} [doc] a document to compare. If falsy, will always return "false". * @return {Boolean} * @api public * @memberOf Document * @instance */Document.prototype.equals = function(doc) { if (!doc) { return false; } const tid = this.$__getValue('_id'); const docid = doc.$__ != null ? doc.$__getValue('_id') : doc; if (!tid && !docid) { return deepEqual(this, doc); } return tid && tid.equals ? tid.equals(docid) : tid === docid;};
/** * Populates paths on an existing document. * * #### Example: * * // Given a document, `populate()` lets you pull in referenced docs * await doc.populate([ * 'stories', * { path: 'fans', sort: { name: -1 } } * ]); * doc.populated('stories'); // Array of ObjectIds * doc.stories[0].title; // 'Casino Royale' * doc.populated('fans'); // Array of ObjectIds * * // If the referenced doc has been deleted, `populate()` will * // remove that entry from the array. * await Story.delete({ title: 'Casino Royale' }); * await doc.populate('stories'); // Empty array * * // You can also pass additional query options to `populate()`, * // like projections: * await doc.populate('fans', '-email'); * doc.fans[0].email // undefined because of 2nd param `select` * * @param {String|Object|Array} path either the path to populate or an object specifying all parameters, or either an array of those * @param {Object|String} [select] Field selection for the population query * @param {Model} [model] The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's `ref` field. * @param {Object} [match] Conditions for the population query * @param {Object} [options] Options for the population query (sort, etc) * @param {String} [options.path=null] The path to populate. * @param {string|PopulateOptions} [options.populate=null] Recursively populate paths in the populated documents. See [deep populate docs](/docs/populate.html#deep-populate). * @param {boolean} [options.retainNullValues=false] by default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries. * @param {boolean} [options.getters=false] if true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options). * @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them. * @param {Object|Function} [options.match=null] Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object. * @param {Function} [options.transform=null] Function that Mongoose will call on every populated document that allows you to transform the populated document. * @param {Object} [options.options=null] Additional options like `limit` and `lean`. * @param {Function} [callback] Callback * @see population /docs/populate * @see Query#select #query_Query-select * @see Model.populate #model_Model-populate * @memberOf Document * @instance * @return {Promise|null} Returns a Promise if no `callback` is given. * @api public */Document.prototype.populate = function populate() { const pop = {}; const args = [...arguments]; let fn; if (args.length !== 0) { if (typeof args[args.length - 1] === 'function') { fn = args.pop(); } // use hash to remove duplicate paths const res = utils.populate.apply(null, args); for (const populateOptions of res) { pop[populateOptions.path] = populateOptions; } } const paths = utils.object.vals(pop); let topLevelModel = this.constructor; if (this.$__isNested) { topLevelModel = this.$__[scopeSymbol].constructor; const nestedPath = this.$__.nestedPath; paths.forEach(function(populateOptions) { populateOptions.path = nestedPath + '.' + populateOptions.path; }); } // Use `$session()` by default if the document has an associated session // See gh-6754 if (this.$session() != null) { const session = this.$session(); paths.forEach(path => { if (path.options == null) { path.options = { session: session }; return; } if (!('session' in path.options)) { path.options.session = session; } }); } paths.forEach(p => { p._localModel = topLevelModel; }); return topLevelModel.populate(this, paths, fn);};
/** * Gets all populated documents associated with this document. * * @api public * @return {Document[]} array of populated documents. Empty array if there are no populated documents associated with this document. * @memberOf Document * @method $getPopulatedDocs * @instance */Document.prototype.$getPopulatedDocs = function $getPopulatedDocs() { let keys = []; if (this.$__.populated != null) { keys = keys.concat(Object.keys(this.$__.populated)); } let result = []; for (const key of keys) { const value = this.$get(key); if (Array.isArray(value)) { result = result.concat(value); } else if (value instanceof Document) { result.push(value); } } return result;};
/** * Gets _id(s) used during population of the given `path`. * * #### Example: * * const doc = await Model.findOne().populate('author'); * * console.log(doc.author.name); // Dr.Seuss * console.log(doc.populated('author')); // '5144cf8050f071d979c118a7' * * If the path was not populated, returns `undefined`. * * @param {String} path * @param {Any} [val] * @param {Object} [options] * @return {Array|ObjectId|Number|Buffer|String|undefined} * @memberOf Document * @instance * @api public */Document.prototype.populated = function(path, val, options) { // val and options are internal if (val == null || val === true) { if (!this.$__.populated) { return undefined; } if (typeof path !== 'string') { return undefined; } // Map paths can be populated with either `path.$*` or just `path` const _path = path.endsWith('.$*') ? path.replace(/\.\$\*$/, '') : path; const v = this.$__.populated[_path]; if (v) { return val === true ? v : v.value; } return undefined; } this.$__.populated || (this.$__.populated = {}); this.$__.populated[path] = { value: val, options: options }; // If this was a nested populate, make sure each populated doc knows // about its populated children (gh-7685) const pieces = path.split('.'); for (let i = 0; i < pieces.length - 1; ++i) { const subpath = pieces.slice(0, i + 1).join('.'); const subdoc = this.$get(subpath); if (subdoc != null && subdoc.$__ != null && this.$populated(subpath)) { const rest = pieces.slice(i + 1).join('.'); subdoc.$populated(rest, val, options); // No need to continue because the above recursion should take care of // marking the rest of the docs as populated break; } } return val;};
/** * Alias of [`.populated`](#document_Document-populated). * * @method $populated * @memberOf Document * @api public */Document.prototype.$populated = Document.prototype.populated;
/** * Throws an error if a given path is not populated * * #### Example: * * const doc = await Model.findOne().populate('author'); * * doc.$assertPopulated('author'); // does not throw * doc.$assertPopulated('other path'); // throws an error * * // Manually populate and assert in one call. The following does * // `doc.$set({ likes })` before asserting. * doc.$assertPopulated('likes', { likes }); * * * @param {String|String[]} path path or array of paths to check. `$assertPopulated` throws if any of the given paths is not populated. * @param {Object} [values] optional values to `$set()`. Convenient if you want to manually populate a path and assert that the path was populated in 1 call. * @return {Document} this * @memberOf Document * @method $assertPopulated * @instance * @api public */Document.prototype.$assertPopulated = function $assertPopulated(path, values) { if (Array.isArray(path)) { path.forEach(p => this.$assertPopulated(p, values)); return this; } if (arguments.length > 1) { this.$set(values); } if (!this.$populated(path)) { throw new MongooseError(`Expected path "${path}" to be populated`); } return this;};
/** * Takes a populated field and returns it to its unpopulated state. * * #### Example: * * Model.findOne().populate('author').exec(function (err, doc) { * console.log(doc.author.name); // Dr.Seuss * console.log(doc.depopulate('author')); * console.log(doc.author); // '5144cf8050f071d979c118a7' * }) * * If the path was not provided, then all populated fields are returned to their unpopulated state. * * @param {String|String[]} [path] Specific Path to depopulate. If unset, will depopulate all paths on the Document. Or multiple space-delimited paths. * @return {Document} this * @see Document.populate #document_Document-populate * @api public * @memberOf Document * @instance */Document.prototype.depopulate = function(path) { if (typeof path === 'string') { path = path.indexOf(' ') === -1 ? [path] : path.split(' '); } let populatedIds; const virtualKeys = this.$$populatedVirtuals ? Object.keys(this.$$populatedVirtuals) : []; const populated = this.$__ && this.$__.populated || {}; if (arguments.length === 0) { // Depopulate all for (const virtualKey of virtualKeys) { delete this.$$populatedVirtuals[virtualKey]; delete this._doc[virtualKey]; delete populated[virtualKey]; } const keys = Object.keys(populated); for (const key of keys) { populatedIds = this.$populated(key); if (!populatedIds) { continue; } delete populated[key]; utils.setValue(key, populatedIds, this._doc); } return this; } for (const singlePath of path) { populatedIds = this.$populated(singlePath); delete populated[singlePath]; if (virtualKeys.indexOf(singlePath) !== -1) { delete this.$$populatedVirtuals[singlePath]; delete this._doc[singlePath]; } else if (populatedIds) { utils.setValue(singlePath, populatedIds, this._doc); } } return this;};

/** * Returns the full path to this document. * * @param {String} [path] * @return {String} * @api private * @method $__fullPath * @memberOf Document * @instance */Document.prototype.$__fullPath = function(path) { // overridden in SubDocuments return path || '';};
/** * Returns the changes that happened to the document * in the format that will be sent to MongoDB. * * #### Example: * * const userSchema = new Schema({ * name: String, * age: Number, * country: String * }); * const User = mongoose.model('User', userSchema); * const user = await User.create({ * name: 'Hafez', * age: 25, * country: 'Egypt' * }); * * // returns an empty object, no changes happened yet * user.getChanges(); // { } * * user.country = undefined; * user.age = 26; * * user.getChanges(); // { $set: { age: 26 }, { $unset: { country: 1 } } } * * await user.save(); * * user.getChanges(); // { } * * Modifying the object that `getChanges()` returns does not affect the document's * change tracking state. Even if you `delete user.getChanges().$set`, Mongoose * will still send a `$set` to the server. * * @return {Object} * @api public * @method getChanges * @memberOf Document * @instance */Document.prototype.getChanges = function() { const delta = this.$__delta(); const changes = delta ? delta[1] : {}; return changes;};
/*! * Module exports. */Document.ValidationError = ValidationError;module.exports = exports = Document;
mongoose

Version Info

Tagged at
a year ago