时间:2021-07-01 10:21:17 帮助过:10人阅读
let MongoDB = require("mongodb")
let MongoClient = MongoDB.MongoClient
let ObjectID = MongoDB.ObjectID
class Db{
static getInstance(){
if(!Db.instance){
Db.instance=new Db()
}
return Db.instance
}
constructor(){
this.dbClient="";
this.connect();
}
connect(){
let that = this;
return new Promise((res,rej)=>{
if(!that.dbClient){
MongoClient.connect(‘mongodb://localhost:27017/‘,{ useUnifiedTopology: true},(err,client)=>{
if(err){
rej(err)
}else{
that.dbClient=client.db("koa")
res(that.dbClient)
}
})
}else{
res(that.dbClient)
}
})
}
find(collectionName,json){
return new Promise((res,rej)=>{
this.connect().then(db=>{
let result = db.collection(collectionName).find(json);
result.toArray((err,docs)=>{
if(err){
rej(err)
return
}
res(docs)
})
})
})
}
update(collectionName,json1,json2){
return new Promise((res,rej)=>{
this.connect().then((db)=>{
db.collection(collectionName).updateOne(json1,{
$set:json2
},(err,result)=>{
if(err){
rej(err)
}else{
res(result)
}
})
})
})
}
insert(collectionName,json){
return new Promise((res,rej)=>{
this.connect().then((db)=>{
db.collection(collectionName).insertOne(json,(err,result)=>{
if(err){
rej(err)
}else{
res(result)
}
})
})
})
}
remove(collectionName,json){
return new Promise((res,rej)=>{
this.connect().then((db)=>{
db.collection(collectionName).removeOne(json,(err,result)=>{
if(err){
rej(err)
}else{
res(result)
}
})
})
})
}
}
module.exports=Db.getInstance();
Node.JS中使用单例封装MongoDB
标签:else update array export cal struct static mis mongod