标签:else update array export cal struct static mis mongod
在Node.JS中使用MongoDB操作数据库时,通常需要调用connnet方法连接数据库后使用它返回的db对象进行操作,这样就导致了每次操作数据库时都需要连接数据库才能返回一个db对象,下面代码使用了单例进行封装,这样封装可以是db对象用于暴露出来,不用每次操作数据库都使用connet方法,极大提高了MongoDB的性能
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();
标签:else update array export cal struct static mis mongod
原文地址:https://www.cnblogs.com/shuaigebie/p/13114713.html