我不确定是否有必要处理mongoClient.close()异常。
这是我的代码:
import { Db, MongoClient, InsertOneWriteOpResult, InsertWriteOpResult } from 'mongodb';
import { connect, dbname } from '../connecting';
connect().then(async (mongoClient: MongoClient | null) => {
if (mongoClient) {
const db: Db = mongoClient.db(dbname);
// insert a single document
const ro: InsertOneWriteOpResult = await db.collection('inserts').insertOne({ a: 1 });
console.log('ro.insertedCount: ', ro.insertedCount);
// insert multiple documents
const rm: InsertWriteOpResult = await db.collection('inserts').insertMany([{ a: 2 }, { a: 3 }]);
console.log('rm.insertedCount:', rm.insertedCount);
try {
await mongoClient.close();
console.log('mongo client close successfully');
} catch (err) {
console.log('mongo client close failed');
}
}
});
因为mongoClient.close()
的值是promise
。
我应该使用try/catch
处理mongo客户端关闭失败的异常吗?生产环境是否需要?
更新1
这是我的connect
函数:
import { MongoClient } from 'mongodb';
const dbname: string = 'mongodb-research';
async function connect(): Promise<MongoClient | null> {
const uri: string = `mongodb://localhost:27017/`;
try {
const mongoClient: MongoClient = await MongoClient.connect(
uri,
{ useNewUrlParser: true }
);
console.log('connected correctly to server');
return mongoClient;
} catch (err) {
console.log(err);
return null;
}
}
export { connect, dbname };
我在connect
函数中而不是在父模块中捕获了connect
异常。