-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindPage.examples.js
More file actions
1438 lines (1263 loc) · 48.7 KB
/
findPage.examples.js
File metadata and controls
1438 lines (1263 loc) · 48.7 KB
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
/**
* findPage 方法完整示例集
* 演示各种使用场景和最佳实践
*/
const MonSQLize = require('../lib');
const { stopMemoryServer } = require('../lib/mongodb/connect');
// ============================================================================
// 常量配置
// ============================================================================
// MongoDB 连接配置
const DB_CONFIG = {
type: 'mongodb',
databaseName: 'ecommerce',
config: { useMemoryServer: true }
};
// 集合名称常量
const COLLECTIONS = {
USERS: 'users',
PRODUCTS: 'products',
ORDERS: 'orders',
CATEGORIES: 'categories',
SETTINGS: 'settings'
};
// 数据量配置
const DATA_SIZE = {
USERS: 50,
PRODUCTS: 100,
ORDERS: 150
};
// ============================================================================
// 数据准备和清理工具函数
// ============================================================================
// 全局标志:标记索引是否已经检查过
let indexesChecked = false;
// 全局标志:标记是否已经提示过数据存在
let dataExistenceNotified = false;
// 全局标志:标记是否已经提示过无需清理
let cleanupNotified = false;
/**
* 创建 MonSQLize 实例
* @returns {MonSQLize} MonSQLize 实例
*/
function createMonSQLizeInstance() {
return new MonSQLize(DB_CONFIG);
}
/**
* 生成用户数据
* @param {number} count - 生成数量
* @returns {Array} 用户数据数组
*/
function generateUsers(count) {
const users = [];
for (let i = 1; i <= count; i++) {
users.push({
userId: `USER-${String(i).padStart(5, '0')}`,
name: `用户${i}`,
username: i % 2 === 0 ? `user${i}` : `User${i}`,
email: `user${i}@example.com`,
status: i % 5 === 0 ? 'inactive' : 'active',
active: i % 5 !== 0,
role: i % 10 === 0 ? 'admin' : i % 15 === 0 ? 'vip' : 'user',
totalSpent: Math.floor(Math.random() * 20000),
orderCount: Math.floor(Math.random() * 100),
level: Math.floor(Math.random() * 10) + 1,
verified: i % 3 !== 0,
avatar: `avatar${i}.jpg`,
createdAt: new Date(Date.now() - i * 86400000 * 2),
updatedAt: new Date()
});
}
return users;
}
/**
* 生成商品数据
* @param {number} count - 生成数量
* @returns {Array} 商品数据数组
*/
function generateProducts(count) {
const products = [];
const categories = ['electronics', 'books', 'clothing'];
for (let i = 1; i <= count; i++) {
products.push({
productId: `PROD-${String(i).padStart(5, '0')}`,
name: `商品${i}`,
description: `这是商品${i}的详细描述`,
category: categories[i % 3],
language: i % 5 === 0 ? 'zh' : 'en',
price: Math.floor(Math.random() * 1000) + 50,
inStock: i % 4 !== 0,
sales: Math.floor(Math.random() * 2000),
hot: i % 10 === 0,
rating: 3 + Math.random() * 2,
tags: i % 3 === 0 ? ['electronics', 'sale'] : ['test'],
image: `product${i}.jpg`,
publishDate: new Date(Date.now() - Math.random() * 365 * 86400000),
reviews: [{ rating: 4.5 }],
createdAt: new Date(Date.now() - i * 43200000),
updatedAt: new Date()
});
}
return products;
}
/**
* 生成订单数据
* @param {number} count - 生成数量
* @returns {Array} 订单数据数组
*/
function generateOrders(count) {
const orders = [];
const statuses = ['pending', 'paid', 'completed'];
for (let i = 1; i <= count; i++) {
const status = statuses[i % 3];
const createdAt = new Date(Date.now() - i * 21600000);
orders.push({
orderId: `ORD-${String(i).padStart(5, '0')}`,
status,
amount: Math.floor(Math.random() * 2000) + 100,
items: Math.floor(Math.random() * 5) + 1,
priority: Math.floor(Math.random() * 3),
customerId: `USER-${String((i % 50) + 1).padStart(5, '0')}`,
createdAt,
completedAt: status === 'completed' ? new Date(createdAt.getTime() + 3600000) : null,
updatedAt: new Date()
});
}
return orders;
}
/**
* 准备示例数据
* @param {Object} msq - MonSQLize 实例
* @param {boolean} [skipIndexCheck=false] - 是否跳过索引检查(默认不跳过)
*/
async function prepareExampleData(msq, skipIndexCheck = false) {
// 只在第一次准备数据时输出提示
if (!dataExistenceNotified) {
console.log('🔧 准备示例数据...');
}
const db = msq._adapter.db;
// 检查是否已有数据
const usersCount = await db.collection(COLLECTIONS.USERS).countDocuments();
const productsCount = await db.collection(COLLECTIONS.PRODUCTS).countDocuments();
const ordersCount = await db.collection(COLLECTIONS.ORDERS).countDocuments();
if (usersCount > 0 && productsCount > 0 && ordersCount > 0) {
// 只在第一次发现数据时提示
if (!dataExistenceNotified) {
console.log('✅ 数据库已有数据,跳过插入');
dataExistenceNotified = true;
}
// 只在需要时检查索引(且未检查过)
if (!skipIndexCheck && !indexesChecked) {
await ensureIndexes(db);
indexesChecked = true;
}
return { needCleanup: false };
}
console.log('📝 插入示例数据...');
dataExistenceNotified = true;
// 插入用户数据
const users = generateUsers(DATA_SIZE.USERS);
await db.collection(COLLECTIONS.USERS).insertMany(users);
console.log(` ✅ 插入 ${users.length} 条用户数据`);
// 插入商品数据
const products = generateProducts(DATA_SIZE.PRODUCTS);
await db.collection(COLLECTIONS.PRODUCTS).insertMany(products);
console.log(` ✅ 插入 ${products.length} 条商品数据`);
// 插入订单数据
const orders = generateOrders(DATA_SIZE.ORDERS);
await db.collection(COLLECTIONS.ORDERS).insertMany(orders);
console.log(` ✅ 插入 ${orders.length} 条订单数据`);
// 插入分类数据
const categories_data = [
{ name: '电子产品', slug: 'electronics', enabled: true, order: 1 },
{ name: '图书', slug: 'books', enabled: true, order: 2 },
{ name: '服装', slug: 'clothing', enabled: true, order: 3 },
{ name: '食品', slug: 'food', enabled: false, order: 4 }
];
await db.collection(COLLECTIONS.CATEGORIES).insertMany(categories_data);
console.log(` ✅ 插入 ${categories_data.length} 条分类数据`);
// 插入配置数据
const settings = [
{ type: 'system', key: 'siteName', value: 'My Shop' },
{ type: 'system', key: 'language', value: 'zh-CN' },
{ type: 'user', key: 'theme', value: 'dark' }
];
await db.collection(COLLECTIONS.SETTINGS).insertMany(settings);
console.log(` ✅ 插入 ${settings.length} 条配置数据`);
console.log('✅ 示例数据准备完成\n');
// 创建必要的索引(只在未检查过时执行)
if (!skipIndexCheck && !indexesChecked) {
await ensureIndexes(db);
indexesChecked = true;
}
return { needCleanup: true };
}
/**
* 确保所有必要的索引存在
*/
async function ensureIndexes(db) {
console.log('🔧 检查并创建索引...');
const indexes = [
{
collection: COLLECTIONS.ORDERS,
spec: { status: 1, createdAt: -1 },
name: 'status_createdAt_idx',
description: '订单状态和创建时间索引'
},
{
collection: COLLECTIONS.ORDERS,
spec: { status: 1, amount: 1 },
name: 'status_amount_idx',
description: '订单状态和金额索引'
},
{
collection: COLLECTIONS.PRODUCTS,
spec: { category: 1, price: -1 },
name: 'category_price_idx',
description: '商品分类和价格索引'
},
{
collection: COLLECTIONS.PRODUCTS,
spec: { inStock: 1, sales: -1 },
name: 'inStock_sales_idx',
description: '商品库存和销量索引'
},
{
collection: COLLECTIONS.PRODUCTS,
spec: { hot: 1, inStock: 1 },
name: 'hot_inStock_idx',
description: '热门商品和库存索引'
},
{
collection: COLLECTIONS.USERS,
spec: { status: 1, createdAt: -1 },
name: 'status_createdAt_idx',
description: '用户状态和创建时间索引'
},
{
collection: COLLECTIONS.CATEGORIES,
spec: { enabled: 1, order: 1 },
name: 'enabled_order_idx',
description: '分类启用状态和排序索引'
},
{
collection: COLLECTIONS.SETTINGS,
spec: { type: 1, key: 1 },
name: 'type_key_idx',
description: '配置类型和键索引'
},
// findPage 示例8需要的演示索引
{
collection: COLLECTIONS.ORDERS,
spec: { status: 1, createdAt: -1 },
name: 'demo_status_createdAt_idx',
description: '示例8演示用:订单状态和时间复合索引',
demo: true
},
{
collection: COLLECTIONS.PRODUCTS,
spec: { category: 1, price: 1 },
name: 'demo_category_price_idx',
description: '示例8演示用:商品分类和价格复合索引',
demo: true
}
];
for (const indexDef of indexes) {
try {
const coll = db.collection(indexDef.collection);
// 检查索引是否已存在
const existingIndexes = await coll.indexes();
const indexExists = existingIndexes.some(idx => idx.name === indexDef.name);
if (!indexExists) {
await coll.createIndex(indexDef.spec, { name: indexDef.name });
console.log(` ✅ 创建索引: ${indexDef.collection}.${indexDef.name}${indexDef.demo ? ' (演示用)' : ''}`);
} else {
console.log(` ⏭️ 索引已存在: ${indexDef.collection}.${indexDef.name}`);
}
} catch (error) {
console.log(` ⚠️ 索引创建失败 ${indexDef.collection}.${indexDef.name}: ${error.message}`);
// 继续创建其他索引,不中断流程
}
}
console.log('✅ 索引检查完成\n');
}
/**
* 清理示例数据
*/
async function cleanupExampleData(msq, needCleanup) {
if (!needCleanup) {
// 只在第一次提示无需清理
if (!cleanupNotified) {
console.log('\n✅ 使用的是已有数据,无需清理');
cleanupNotified = true;
}
return;
}
console.log('\n🧹 清理示例数据...');
const db = msq._adapter.db;
// 使用常量清理集合
const collectionList = Object.values(COLLECTIONS);
for (const collName of collectionList) {
await db.collection(collName).deleteMany({});
}
// 可选:清理创建的索引
console.log('🧹 清理索引...');
for (const collName of collectionList) {
try {
const coll = db.collection(collName);
const indexes = await coll.indexes();
// 删除非 _id 的自定义索引
for (const idx of indexes) {
if (idx.name !== '_id_' && idx.name.endsWith('_idx')) {
try {
await coll.dropIndex(idx.name);
console.log(` ✅ 删除索引: ${collName}.${idx.name}`);
} catch (error) {
// 索引可能已被删除,忽略错误
}
}
}
} catch (error) {
// 集合可能不存在,忽略错误
}
}
console.log('✅ 示例数据清理完成');
}
// ============================================================================
// 示例 1: 基础游标分页
// ============================================================================
async function example1_basicCursorPagination() {
console.log('\n📖 示例 1: 基础游标分页');
console.log('='.repeat(60));
const msq = createMonSQLizeInstance();
const { collection } = await msq.connect();
// 准备数据
const { needCleanup } = await prepareExampleData(msq);
try {
// 获取第一页
console.log('\n1️⃣ 获取第一页数据:');
const page1 = await collection(COLLECTIONS.PRODUCTS).findPage({
query: { category: 'electronics', inStock: true },
sort: { price: 1, _id: 1 },
limit: 20
});
console.log(` - 返回 ${page1.items.length} 条商品`);
console.log(` - 有下一页: ${page1.pageInfo.hasNext}`);
if (page1.items.length > 0) {
console.log(` - 价格区间: ${page1.items[0]?.price} ~ ${page1.items[page1.items.length - 1]?.price}`);
}
// 获取下一页
if (page1.pageInfo.hasNext) {
console.log('\n2️⃣ 获取下一页:');
const page2 = await collection(COLLECTIONS.PRODUCTS).findPage({
query: { category: 'electronics', inStock: true },
sort: { price: 1, _id: 1 },
limit: 20,
after: page1.pageInfo.endCursor
});
console.log(` - 返回 ${page2.items.length} 条商品`);
console.log(` - 有上一页: ${page2.pageInfo.hasPrev}`);
console.log(` - 有下一页: ${page2.pageInfo.hasNext}`);
}
} finally {
await cleanupExampleData(msq, needCleanup);
await msq.close();
}
console.log('\n✅ 示例 1 完成\n');
}
// ============================================================================
// 示例 2: 跳页功能
// ============================================================================
async function example2_pageJumping() {
console.log('\n📖 示例 2: 跳页功能');
console.log('='.repeat(60));
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'ecommerce',
config: { useMemoryServer: true },
bookmarks: {
step: 10, // 每 10 页保存一次书签
maxHops: 20, // 最多跳 20 次
ttlMs: 3600000 // 书签缓存 1 小时
}
});
const { collection } = await msq.connect();
// 使用书签跳转到第 5 页
console.log('\n1️⃣ 跳转到第 5 页:');
const page5 = await collection('orders').findPage({
query: { status: 'completed' },
sort: { completedAt: -1, _id: 1 },
limit: 50,
page: 5,
jump: {
step: 10,
maxHops: 20
}
});
console.log(` - 当前页: ${page5.pageInfo.currentPage}`);
console.log(` - 返回 ${page5.items.length} 条订单`);
// 使用 offset 跳转(适合小数据量)
console.log('\n2️⃣ 使用 offset 跳转到第 3 页:');
const page3 = await collection('orders').findPage({
query: { status: 'pending' },
sort: { createdAt: -1 },
limit: 30,
page: 3,
offsetJump: {
enable: true,
maxSkip: 10000
}
});
console.log(` - 当前页: ${page3.pageInfo.currentPage}`);
console.log(` - 返回 ${page3.items.length} 条订单`);
await msq.close();
console.log('\n✅ 示例 2 完成\n');
}
// ============================================================================
// 示例 3: 流式处理大数据集
// ============================================================================
async function example3_streamProcessing() {
console.log('\n📖 示例 3: 流式处理大数据集');
console.log('='.repeat(60));
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'ecommerce',
config: { useMemoryServer: true },
findPageMaxLimit: 100000 // 提高流式查询的限制
});
const { collection } = await msq.connect();
// 流式处理订单统计
console.log('\n1️⃣ 流式统计 2024 年所有订单:');
const stream = await collection('orders').findPage({
query: {
createdAt: {
$gte: new Date('2024-01-01'),
$lt: new Date('2025-01-01')
}
},
sort: { createdAt: 1 },
limit: 100000,
stream: true,
batchSize: 1000
});
let totalOrders = 0;
let totalAmount = 0;
const statusCount = {};
stream.on('data', (order) => {
totalOrders++;
totalAmount += order.amount || 0;
statusCount[order.status] = (statusCount[order.status] || 0) + 1;
// 每 1000 条输出一次进度
if (totalOrders % 1000 === 0) {
process.stdout.write(`\r - 已处理: ${totalOrders} 条订单...`);
}
});
await new Promise((resolve, reject) => {
stream.on('end', () => {
if (totalOrders > 0) {
console.log(`\n - 总订单数: ${totalOrders}`);
console.log(` - 总金额: ${totalAmount.toFixed(2)}`);
console.log(` - 平均订单金额: ${(totalAmount / totalOrders).toFixed(2)}`);
console.log(' - 状态分布:', statusCount);
} else {
console.log('\n - 没有找到 2024 年的订单数据');
}
resolve();
});
stream.on('error', (err) => {
console.error(' ❌ 流处理错误:', err);
reject(err);
});
});
await msq.close();
console.log('\n✅ 示例 3 完成\n');
}
// ============================================================================
// 示例 4: 获���总数统计
// ============================================================================
async function example4_totalsStatistics() {
console.log('\n📖 示例 4: 获取总数统计');
console.log('='.repeat(60));
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'ecommerce',
config: { useMemoryServer: true }
});
const { collection } = await msq.connect();
// 同步获取总数
console.log('\n1️⃣ 同步获取总数:');
const pageSync = await collection('users').findPage({
query: { active: true },
sort: { createdAt: -1 },
limit: 20,
totals: {
mode: 'sync',
maxTimeMS: 5000
}
});
console.log(` - 当前页数据: ${pageSync.items.length} 条`);
if (pageSync.totals) {
console.log(` - 总用户数: ${pageSync.totals.total}`);
console.log(` - 总页数: ${pageSync.totals.totalPages}`);
console.log(` - 统计时间戳: ${new Date(pageSync.totals.ts).toLocaleString()}`);
} else {
console.log(' ⚠️ totals 功能未实现');
}
// 异步获取总数
console.log('\n2️⃣ 异步获取总数(首次查询):');
const pageAsync1 = await collection('products').findPage({
query: { category: 'books' },
sort: { publishDate: -1 },
limit: 30,
totals: { mode: 'async' }
});
console.log(` - 当前页数据: ${pageAsync1.items.length} 条`);
if (pageAsync1.totals) {
console.log(` - 总数: ${pageAsync1.totals.total === null ? '计算中...' : pageAsync1.totals.total}`);
console.log(` - Token: ${pageAsync1.totals.token}`);
// 等待后台统计完成
if (pageAsync1.totals.total === null) {
console.log('\n 等待 2 秒后重新查询...');
await new Promise(resolve => setTimeout(resolve, 2000));
const pageAsync2 = await collection('products').findPage({
query: { category: 'books' },
sort: { publishDate: -1 },
limit: 30,
totals: { mode: 'async' }
});
if (pageAsync2.totals) {
console.log(` - 总数: ${pageAsync2.totals.total}`);
console.log(` - 总页数: ${pageAsync2.totals.totalPages}`);
}
}
} else {
console.log(' ⚠️ totals 功能未实现');
}
await msq.close();
console.log('\n✅ 示例 4 完成\n');
}
// ============================================================================
// 示例 5: 复杂查询和聚合
// ============================================================================
async function example5_complexQueries() {
console.log('\n📖 示例 5: 复杂查询和聚合');
console.log('='.repeat(60));
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'ecommerce',
config: { useMemoryServer: true }
});
const { collection } = await msq.connect();
// 复合排序
console.log('\n1️⃣ 多字段复合排序:');
const result1 = await collection('orders').findPage({
query: {
status: { $in: ['paid', 'completed'] }
},
sort: {
priority: -1, // 优先级降序
amount: -1, // 金额降序
createdAt: -1, // 时间降序
_id: 1 // ID 升序(保证稳定性)
},
limit: 10
});
console.log(` - 返回 ${result1.items.length} 条订单`);
result1.items.slice(0, 3).forEach((order, i) => {
console.log(` - #${i + 1}: 优先级=${order.priority}, 金额=${order.amount}`);
});
// 使用聚合管道增强数据
console.log('\n2️⃣ 附加聚合管道计算:');
const result2 = await collection('orders').findPage({
query: { status: 'completed' },
sort: { completedAt: -1 },
limit: 10,
pipeline: [
{
$addFields: {
// 计算税后金额
amountWithTax: { $multiply: ['$amount', 1.13] },
// 计算完成天数
daysToComplete: {
$divide: [
{ $subtract: ['$completedAt', '$createdAt'] },
86400000 // 毫秒转天数
]
}
}
},
{
$addFields: {
// 添加处理速度标签
speedLabel: {
$switch: {
branches: [
{ case: { $lte: ['$daysToComplete', 1] }, then: '快速' },
{ case: { $lte: ['$daysToComplete', 3] }, then: '正常' },
{ case: { $gt: ['$daysToComplete', 3] }, then: '延迟' }
],
default: '未知'
}
}
}
}
]
});
console.log(` - 返回 ${result2.items.length} 条订单`);
result2.items.slice(0, 3).forEach((order, i) => {
console.log(` - #${i + 1}: 金额=${order.amount}, 含税=${order.amountWithTax?.toFixed(2)}, 速度=${order.speedLabel}`);
});
// 使用索引提示优化查询
console.log('\n3️⃣ 使用索引提示优化查询(示例):');
console.log(' - 注意:需要先创建索引: db.products.createIndex({ category: 1, price: 1 })');
// 不使用 hint 参数,避免索引不存在的错误
const result3 = await collection('products').findPage({
query: {
category: 'electronics',
price: { $gte: 100, $lte: 1000 }
},
sort: { price: 1 },
limit: 20,
maxTimeMS: 3000
});
console.log(` - 返回 ${result3.items.length} 条商品`);
await msq.close();
console.log('\n✅ 示例 5 完成\n');
}
// ============================================================================
// 示例 6: 错误处理和重试
// ============================================================================
async function example6_errorHandling() {
console.log('\n📖 示例 6: 错误处理和重试');
console.log('='.repeat(60));
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'ecommerce',
config: { useMemoryServer: true }
});
const { collection } = await msq.connect();
// 处理跳页距离过大
console.log('\n1️⃣ 处理跳页距离过大错误:');
try {
await collection('orders').findPage({
query: {},
sort: { _id: 1 },
limit: 10,
page: 1000,
jump: { maxHops: 5 }
});
} catch (error) {
if (error.code === 'JUMP_TOO_FAR') {
console.log(' ⚠️ 跳页距离过大,切换到 offset 模式:');
const result = await collection('orders').findPage({
query: {},
sort: { _id: 1 },
limit: 10,
page: 1000,
offsetJump: {
enable: true,
maxSkip: 100000
}
});
console.log(` ✅ 成功获取第 ${result.pageInfo.currentPage} 页`);
}
}
// 处理参数冲突
console.log('\n2️⃣ 处理参数冲突错误:');
try {
await collection('orders').findPage({
query: {},
sort: { _id: 1 },
limit: 10,
page: 2,
after: 'some-cursor'
});
} catch (error) {
if (error.code === 'VALIDATION_ERROR') {
console.log(' ⚠️ 参数冲突: page 和 after 不能同时使用');
console.log(' 📝 错误详情:', error.details);
console.log(' ✅ 移除 page 参数后重试');
}
}
// 处理超时
console.log('\n3️⃣ 处理查询超时:');
const queryWithRetry = async (retries = 3) => {
for (let i = 0; i < retries; i++) {
try {
const result = await collection('large_collection').findPage({
query: { /* 复杂查询 */ },
sort: { _id: 1 },
limit: 100,
maxTimeMS: 5000
});
return result;
} catch (error) {
if (error.code === 50 && i < retries - 1) { // MongoDB 超时错误码
console.log(` ⚠️ 第 ${i + 1} 次尝试超时,重试中...`);
await new Promise(resolve => setTimeout(resolve, 1000));
} else {
throw error;
}
}
}
};
console.log(' ✅ 实现了带重试的查询逻辑');
await msq.close();
console.log('\n✅ 示例 6 完成\n');
}
// ============================================================================
// 示例 7: 实战场景 - 构建分页 API
// ============================================================================
async function example7_buildPaginationAPI() {
console.log('\n📖 示例 7: 实战场景 - 构建分页 API');
console.log('='.repeat(60));
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'ecommerce',
config: { useMemoryServer: true }
});
const { collection } = await msq.connect();
// 模拟 RESTful API 请求处理
async function handleProductListAPI(req) {
const {
category,
minPrice,
maxPrice,
search,
sortBy = 'price',
sortOrder = 'asc',
limit = 20,
after,
page
} = req;
// 构建查询条件
const query = {};
if (category) query.category = category;
if (minPrice || maxPrice) {
query.price = {};
if (minPrice) query.price.$gte = parseFloat(minPrice);
if (maxPrice) query.price.$lte = parseFloat(maxPrice);
}
if (search) {
query.$or = [
{ name: { $regex: search, $options: 'i' } },
{ description: { $regex: search, $options: 'i' } }
];
}
// 构建排序
const sort = {};
sort[sortBy] = sortOrder === 'desc' ? -1 : 1;
sort._id = 1; // 保证稳定排序
// 执行查询(不使用 totals 避免连接问题)
const options = {
query,
sort,
limit: Math.min(parseInt(limit) || 20, 100) // 限制最大 100
};
if (after) {
options.after = after;
} else if (page) {
options.page = parseInt(page);
options.jump = { step: 10, maxHops: 20 };
}
const result = await collection('products').findPage(options);
// 转换为 API 响应格式
return {
success: true,
data: result.items,
pagination: {
hasNextPage: result.pageInfo.hasNext,
hasPreviousPage: result.pageInfo.hasPrev,
nextCursor: result.pageInfo.endCursor,
prevCursor: result.pageInfo.startCursor,
currentPage: result.pageInfo.currentPage
}
};
}
// 模拟几个 API 请求
console.log('\n1️⃣ 请求: GET /api/products?category=electronics&limit=5');
const response1 = await handleProductListAPI({
category: 'electronics',
limit: 5
});
console.log(` - 返回 ${response1.data.length} 条商品`);
console.log(` - 有下一页: ${response1.pagination.hasNextPage}`);
console.log('\n2️⃣ 请求: GET /api/products?category=electronics&page=2&limit=5');
const response2 = await handleProductListAPI({
category: 'electronics',
page: 2,
limit: 5
});
console.log(` - 当前页: ${response2.pagination.currentPage}`);
console.log(` - 返回 ${response2.data.length} 条商品`);
console.log('\n3️⃣ 请求: GET /api/products?minPrice=100&maxPrice=500&sortBy=price&sortOrder=desc');
const response3 = await handleProductListAPI({
minPrice: 100,
maxPrice: 500,
sortBy: 'price',
sortOrder: 'desc',
limit: 10
});
console.log(` - 返回 ${response3.data.length} 条商品`);
if (response3.data.length > 0) {
console.log(` - 价格区间: ${response3.data[response3.data.length - 1]?.price} ~ ${response3.data[0]?.price}`);
}
await msq.close();
console.log('\n✅ 示例 7 完成\n');
}
// ============================================================================
// 示例 8: 性能优化技巧
// ============================================================================
async function example8_performanceOptimization() {
console.log('\n📖 示例 8: 性能优化技巧');
console.log('='.repeat(60));
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'ecommerce',
config: { useMemoryServer: true },
bookmarks: {
step: 10,
maxHops: 20,
ttlMs: 6 * 3600000 // 6 小时
}
});
const { collection } = await msq.connect();
// 获取原生 MongoDB 数据库对象用于索引操作
const nativeDb = msq._adapter.db;
const ordersCollection = nativeDb.collection('orders');
const productsCollection = nativeDb.collection('products');
console.log('\n🔧 准备阶段: 删除可能存在的旧索引...');
try {
await ordersCollection.dropIndex('demo_status_createdAt_idx');
console.log(' ✅ 已删除旧索引: orders.demo_status_createdAt_idx');
} catch (err) {
if (err.code === 27) { // IndexNotFound
console.log(' ℹ️ 索引不存在,跳过删除');
}
}
try {
await productsCollection.dropIndex('demo_category_price_idx');
console.log(' ✅ 已删除旧索引: products.demo_category_price_idx');
} catch (err) {
if (err.code === 27) {
console.log(' ℹ️ 索引不存在,跳过删除');
}
}
try {
// 技巧 1: 对比有索引和无索引的性能差异
console.log('\n1️⃣ 技巧: 索引对查询性能的影响');
console.log(' 📊 测试场景: 查询特定状态的订单并按时间排序');
// 无索引时的性能
console.log('\n ⏱️ 无索引查询(基准测试):');
const start1a = Date.now();
const result1a = await collection('orders').findPage({
query: { status: 'paid' },
sort: { createdAt: -1, _id: 1 },
limit: 50
});
const time1a = Date.now() - start1a;
console.log(` - 查询耗时: ${time1a}ms`);
console.log(` - 返回数据: ${result1a.items.length} 条`);
// 创建索引
console.log('\n 🔧 创建复合索引: { status: 1, createdAt: -1 }');
await ordersCollection.createIndex(
{ status: 1, createdAt: -1 },
{ name: 'demo_status_createdAt_idx' }
);
console.log(' - 索引创建完成');
// 有索引时的性能(让 MongoDB 自动选择)
console.log('\n ⚡ 有索引查询(自动优化):');
const start1b = Date.now();
const result1b = await collection('orders').findPage({
query: { status: 'paid' },
sort: { createdAt: -1, _id: 1 },
limit: 50
});
const time1b = Date.now() - start1b;
console.log(` - 查询耗时: ${time1b}ms`);
console.log(` - 返回数据: ${result1b.items.length} 条`);