const Config = require("./config");
const mongodb = require("mongodb");
const MongoClient = mongodb.MongoClient;
const ObjectId = mongodb.ObjectId;
const client = new MongoClient(Config.dbUrl, { useUnifiedTopology: true });
class Db {
// 解决多次实例化,实例不共享的问题
static getInstance() {
if (!Db.instance) {
Db.instance = new Db();
}
return Db.instance;
}
constructor() {
this.dbClient = "";
this.connect();
}
connect() {
return new Promise((resolve, reject) => {
// 把数据库的连接变成长连接,解决多次连接数据库的操作
if (this.dbClient) {
resolve(this.dbClient);
} else {
client.connect(err => {
if (err) {
reject(err);
} else {
this.dbClient = client.db(Config.dbName);
resolve(this.dbClient);
}
});
}
});
}
find(collectionName, json) {
return new Promise((resolve, reject) => {
this.connect()
.then(db => {
const collection = db.collection(collectionName);
collection.find(json).toArray((err, docs) => {
if (err) {
reject(err);
} else {
resolve(docs);
}
});
})
.catch(err => {
reject(err);
});
});
}
insert(collectionName, json) {
return new Promise((resolve, reject) => {
this.connect()
.then(db => {
const collection = db.collection(collectionName);
collection.insertOne(json, (err, docs) => {
if (err) {
reject(err);
} else {
resolve(docs);
}
});
})
.catch(err => {
reject(err);
});
});
}
update(collectionName, json1, json2) {
return new Promise((resolve, reject) => {
this.connect()
.then(db => {
const collection = db.collection(collectionName);
collection.updateOne(
json1,
{
$set: json2
},
(err, docs) => {
if (err) {
reject(err);
} else {
resolve(docs);
}
}
);
})
.catch(err => {
reject(err);
});
});
}
delete(collectionName, json) {
return new Promise((resolve, reject) => {
this.connect()
.then(db => {
const collection = db.collection(collectionName);
collection.deleteOne(json, (err, docs) => {
if (err) {
reject(err);
} else {
resolve(docs);
}
});
})
.catch(err => {
reject(err);
});
});
}
getObjectId(id) {
return ObjectId(id);
}
}
module.exports = Db.getInstance();
网友评论