Nodejs中mongodb的使用及封装
const { MongoClient } = require('mongodb');
class Database {
constructor(url) {
this.connection = null;
this.url = url;
}
async connect() {
if (this.connection) {
throw new Error('Cannot open a new connection.');
}
try {
this.connection = await MongoClient.connect(this.url, { useNewUrlParser: true, useUnifiedTopology: true });
console.log('Connected to database.');
} catch (error) {
console.error('Error connecting to database:', error);
}
}
collection(name) {
if (!this.connection) {
throw new Error('No connection established to database.');
}
return this.connection.db().collection(name);
}
close() {
if (this.connection) {
this.connection.close();
this.connection = null;
console.log('Connection to database closed.');
}
}
}
module.exports = Database;
这段代码定义了一个名为Database
的类,它封装了连接MongoDB数据库的细节。它提供了一个connect
方法来建立连接,一个collection
方法来获取指定名称的集合,以及一个close
方法来关闭连接。使用时,只需创建Database
类的实例并调用相应的方法。
评论已关闭