我尝试在withConnection()函数中抽象try, catch, finally结构,因此例如upsert()的代码是整洁的。但是它给出了一个错误"MongoExpiredSessionError: Cannot use a session that has ended">
我做错了什么?
import 'dotenv/config';
import { MongoClient, ObjectId } from "mongodb";
export class Base {
constructor(db, collection) {
this.client = new MongoClient(process.env.connection);
this.db = db;
this.collection = collection;
this.con = this.client.db(db).collection(collection);
}
async withConnection(callback) {
await this.client.connect();
try {
return callback();
} catch (err) {
console.log(err);
} finally {
await this.client.close();
}
}
async upsert(query, payload) {
await this.withConnection(() => {
return this.con.updateOne(query, payload, { upsert: true })
})
}
// ...
}
成功了!
import 'dotenv/config';
import { MongoClient, ObjectId } from "mongodb";
export class Base {
constructor(db, collection) {
this.client = new MongoClient(process.env.connection);
this.db = db;
this.collection = collection;
this.con = this.client.db(this.db).collection(this.collection);
}
async withConnection(callback = null) {
await this.client.connect();
try {
return await callback();
} catch (err) {
console.log(err);
} finally {
if (callback !== null) {
await this.client.close();
}
}
}
async upsert(query, payload) {
await this.withConnection(async () => {
return await this.con.updateOne(query, payload, { upsert: true })
})
}
}