MongoDB索引创建与数据查询无输出无报错问题排查
MongoDB代码无输出无报错的问题排查
问题根源分析
- 未定义变量触发静默错误:创建索引时使用了
Dev这个未定义的变量,会直接抛出ReferenceError。但由于错误发生在异步回调的参数定义阶段,无法被你当前的err捕获逻辑处理,导致进程静默终止,既无输出也无报错提示。 - 索引参数格式错误:
createIndex的第一个参数是索引的字段配置,需要指定排序方向(1表示升序,-1表示降序),而非具体值。你写的age: 20是完全错误的索引配置方式。
修正后的代码
const MongoClient = require('mongodb').MongoClient; // 全局捕获未处理的异常,避免静默失败 process.on('uncaughtException', (err) => { console.error('未捕获异常:', err); process.exit(1); }); const url = 'mongodb://127.0.0.1:27017'; const dbName = 'myproject'; function connectDB(){ MongoClient.connect(url, function(err, client) { if (err) { console.error('连接MongoDB失败:', err); return; } console.log("已成功连接服务器"); const db = client.db(dbName); const collection = db.collection('mycollection'); // 为name字段创建升序索引,复合索引可写成{name: 1, age: 1} collection.createIndex({name: 1}, function(err, result) { if (err) { console.error('创建索引失败:', err); client.close(); return; } console.log('索引创建完成:', result); // 查询name为'dev'的文档 collection.find({name: 'dev'}).toArray(function(err, docs) { if (err) { console.error('查询文档失败:', err); client.close(); return; } console.log('查询结果:', docs); client.close(); }); }); }); } connectDB();
内容的提问来源于stack exchange,提问作者Dev Gajjar
相关产品推荐
相关产品推荐

