node操作mongodb封装

2019-11-05  本文已影响0人  范er_er
const MongoDb = require('mongodb');
const MongoClient=MongoDb.MongoClient;
const ObjectID = MongoDb.ObjectID;

const Config=require('./config.js')
class Db{

     //单例模式
     static getInstance(){
        if(!Db.Instance){
            Db.Instance=new Db()
        }
        return Db.Instance
    }

    constructor(){
        this.dbClient=null
        this.connect()
    }

    connect(){
      
        const client = new MongoClient(Config.dbUrl,{ useNewUrlParser: true });
        return new Promise((resolve,reject) =>{
            if(!this.dbClient){
            client.connect(err=>{
                if(err){
                    reject(err)
                }
                else{
                    const db = client.db(Config.dbName);
                    this.dbClient = db
                    resolve(this.dbClient) 
                }
            })}
            else{
                resolve(this.dbClient) 
            }
          
        })
      }

    find(collectionName,json){
        return new Promise((resolve,reject)=>{
            this.connect().then(function(db){
                var result = db.collection(collectionName).find(json)
                result.toArray((err,docs)=>{
                    if(err){
                        reject(err)
                    }else{
                        resolve(docs)
                    }
                })
            })
        })
       
    }

    insert(collectionName,json){
        return new Promise((resolve,reject)=>{
            this.connect().then(db=>{
                db.collection(collectionName).insertOne(json,(err,result)=>{
                    if(err){
                        reject(err)
                    }else{
                        resolve(result)
                    }
                })
            })
        })
    }

    update(collectionName,where,data){
        return new Promise((resolve,reject)=>{
            this.connect().then(db=>{
                db.collection(collectionName).updateOne(where,{
                    $set:data
                },(err,result)=>{
                    if(err){
                        reject(err)
                    }else{
                        resolve(result)
                    }
                })
            })
        })
    }

    remove(collectionName,where){
        return new Promise((resolve,reject)=>{
            this.connect().then(db=>{
                db.collection(collectionName).removeOne(where,(err,result)=>{
                    if(err){
                        reject(err)
                    }else{
                        resolve(result)
                    }
                })
            })
        })
    }

    getObjectId(id){
        return new ObjectID(id)
    }


}

module.exports=Db.getInstance()
上一篇下一篇

猜你喜欢

热点阅读