const Mongo = require('mongodb');
const MongoClient = Mongo.MongoClient;
const ObjectID = Mongo.ObjectID;
const Config = require('./config.js');
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){
MongoClient.connect(Config.url, (err, client)=>{
if(err){
console.log(err);
reject(err);
} else {
let db = client.db(Config.dbName);
this.dbClient = db;
resolve(this.dbClient);
}
})
} else {
resolve(this.dbClient);
}
})
}
find(collecter, json){
return new Promise((resolve, reject)=>{
this.connect().then((db)=>{
let res = db.collection(collecter).find(json);
res.toArray((err, result)=>{
if(err){
reject(err);
} else {
resolve(result);
}
})
})
})
}
insert(collecter, json){
return new Promise((resolve, reject)=>{
this.connect().then((db)=>{
db.collection(collecter).insertOne(json, (err, res)=>{
if(err){
reject(err);
} else {
resolve(res)
}
})
})
})
}
update(collecter,wherejson,updatejson){
return new Promise((resolve, reject)=>{
this.connect().then((db)=>{
db.collection(collecter).updateOne(wherejson, {$set: updatejson}, (err, res)=>{
if(err){
reject(err);
} else {
resolve(res);
}
})
})
})
}
delete(collecter, json){
return new Promise((resolve, reject)=>{
this.connect().then((db)=>{
db.collection(collecter).deleteOne(json, (err, res)=>{
if(err){
reject(err);
} else {
resolve(res);
}
})
})
})
}
getObjectId(id){
return new ObjectID(id);
}
}
module.exports = DB.getInstance();
网友评论