封装MongoDB库

配置 config.js (懂得原理可不配)

let app  = {
    //定义数据库连接的地址 以及配置数据库
 url :'mongodb://localhost:27017/',
 dbName : 'tjt'     // tjt数据库的名称  不懂得看我另一篇文章koa2操作mongdb库
    //nodejs连接数据库
}
module.exports = app 

开始配置 DB-git.js

let Config = require('./config.js') 
console.log(Config) //   { url: 'mongodb://localhost:27017/', dbName: 'tjt' }
//引入mongodb下面的MongoClient
const MongoClient = require('mongodb').MongoClient;
                                //定义数据库连接的地址 以及配置数据库
                                const url = 'mongodb://localhost:27017/';
                                const dbName = 'tjt' // tjt数据库的名称

//单例模式

class DB{
let Config = require('./config.js') 
console.log(Config) //   { url: 'mongodb://localhost:27017/', dbName: 'tjt' }
//引入mongodb下面的MongoClient
const MongoDB = require('mongodb')
const MongoClient = require('mongodb').MongoClient;
const ObjectID = MongoDB.ObjectID;


                                // //定义数据库连接的地址 以及配置数据库
                                // const url = 'mongodb://localhost:27017/';
                                // const dbName = 'tjt' // tjt数据库的名称

//单例模式

class DB{
    static getInstance(){
        if(!DB.instance){  //  多次调用也只会 走一次或多次
            console.log('第一次单例模式走的路线')
            DB.instance = new DB() //因为没有DB.instance 所以就自己创造个实例对象
        }else{
            console.log('第二次..三次...四次都走的路线')
        }
        return DB.instance
    }

    constructor(ele){
        console.log('连接数据库')
                           // this.dbClient = '' 个人感觉没必要
        this.connect()
    }
    connect(){
        //nodejs连接数据库
        return new Promise((resolve,reject)=>{
                            // if(this.dbClient){      
                            //     resolve(this.dbClient) 
                            // }else{         
                MongoClient.connect(Config.url,{useNewUrlParser: true,useUnifiedTopology: true},(err,client)=>{   // Config.url === tjt
                    //{useNewUrlParser: true, useUnifiedTopology: true}解决错误提示问题 
                    if(err){
                        console.log('连接失败')
                        reject(err)
                    }else{
                        console.log('连接成功')
                        const db = client.db(Config.dbName);  // 数据库db对象
                        resolve(db)        // new promise解决异步问题  返回文件对象 //tjt  整个connect() 基本就是db对象 ==>db 
                                // this.dbClient = client.db(Config.dbName)
                                // resolve(this.dbClient )
                                // }
                    }
                })
        })
    }
    insert(collectionName,data){
        return new Promise((resolve,reject)=>{
            this.connect().then(db=>{       // this.connect()  ==== resolve(db)  
                db.collection(collectionName).insertOne(data,(error,result)=>{
                    if(!error){
                        console.log('增加数据成功'); 
                        resolve(result)
                    }else{
                        console.log(error,'增加数据失败');  
                        reject(err)
                    }
                })
            })
        })
    }
    update(collectionName,old_data,new_data){
        return new Promise((resolve,reject)=>{
            this.connect().then(db=>{
             db.collection(collectionName).updateOne(old_data,{$set:new_data})
            })
        })
    }
    delete(collectionName,condition){
        return new Promise((resolve,reject)=>{
            this.connect().then(db=>{
                db.collection(collectionName).deleteOne(condition,function(error,result){
                    if(!error){
                        console.log('删除数据成功'); 
                        resolve(result)
                    }else{
                        console.log(error,'删除数据失败');  
                        reject(error)
                    }
                })
            })
        })
    }
    find(collectionName,condition){
        return new Promise((resolve,reject)=>{
            this.connect().then(db=>{
                db.collection(collectionName).find(condition).toArray((err,arr)=>{ //需要转数组 不然显示不出来
                    if(!err){
                        resolve(arr)    
                        // console.log(arr)  //成功 打印所有数据
                    }else{
                        reject(err)
                        // console.log(err)
                    }
                })
            })
        })
    }
    //封装调用ObjectID的方法 ==>用于获取页面对应服务器的值 类似 btn[i]...
    getObjectID(id){ //固定写法  用于获取_id值下标
        return  new ObjectID(id)  /* 见案例 更改模块操作 let id = ctx.query.id
                                  await DB.find("template",{"_id":DB.getObjectID(id)})  */
    }
}

module.exports =  DB.getInstance()

//外部调用方法 :  a.find('abc',{name="谭金涛"})



//添加
    // new DB().insert('abc',{"name":"封装的数据", "age":9999})  
    // new DB().insert('abc',{"name":"新数据", "age":1}) 

//更改 + 添加
    // new DB().update('abc',{"name":"徐晨彦", "age":22},{"msg":"马克巴卡","flag":true})
    // new DB().update('abc',{"name":"谭金涛", "age":21},{"name":"谭金涛","age":22})

//删除 
    // new DB().delete('abc',{"a":"1", "b":"2"})
    // new DB().delete('abc',{"name":"封装的数据", "age":9999})  

//查找
// console.time('a')
    // new DB().find('abc','')
// console.timeEnd('a')
// console.time('b')
//     new DB().find('abc',{name:"戚思宁"})
// console.timeEnd('b')




测试在其他.js文件中调用其中的方法

let a =  require('./DB-git')
a.find('abc','')
/*


{ url: 'mongodb://localhost:27017/', dbName: 'tjt' }
连接数据库
连接成功
[
  { _id: 5e935e5e25405fbbf88f0d76, name: 'xx', age: 22 },
  { _id: 5e935fc723002d9dd8e36b6f, name: 'xx', age: '21' },
  { _id: 5e935ff523002d9dd8e36b70, name: 'x', age: '20' },
  {
    _id: 5e9435c19b1f109603e8f482,
    name: 'xxxx',
    age: 22,
    msg: '马克巴卡',
    flag: true
  },
  { _id: 5e9435e49b1f109603e8f483, name: 'xxxxx, age: 36 },
  { _id: 5e9435f09b1f109603e8f484, name: 'xxxxx', age: 18 },
  { _id: 5e94360b9b1f109603e8f485, name: 'xxxxx, age: 20 },
  { _id: 5e9436189b1f109603e8f486, name: 'xxxxx', age: 19 },
  { _id: 5e9436229b1f109603e8f487, name: 'xxxxx, age: 29 },
  { _id: 5e9436379b1f109603e8f488, name: 'xxxxx', age: 22 },
  { _id: 5e9436479b1f109603e8f489, name: 'xxxxx, age: 20 },
  { _id: 5e946345f0e0b2b238585e7d, name: 'xxxxx, age: '100' },
  { _id: 5e946bbbc046b8a3a0aabb90, name: 'xxxxx一', age: 27 },
  { _id: 5e94833f27a452b7f4a1f502, name: 'xxxxx', age: 1 },
  { _id: 5e9486088a938fbe80b04ec3, name: 'xxxxx', age: 1 },
  { _id: 5e94870c419109bb00bc6dcc, name: 'xxxxx数据', age: 9999 },
  { _id: 5e94870c419109bb00bc6dcd, name: 'xxxxx', age: 1 }
]


*/

👍 :4.15更新 优化了延迟 1-2ms左右

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • const Mongo = require('mongodb'); const MongoClient = Mon...
    追逐时光的光光阅读 738评论 0 0
  • feisky云计算、虚拟化与Linux技术笔记posts - 1014, comments - 298, trac...
    不排版阅读 3,949评论 0 5
  • 候鸟心恋 别梦长岛海蓝湾 海滩依恋赏情还 茫茫海 存思恋 海螺海贝海瑚珊 海滩故事海浪山 心中有梦 梦境海南 栖息...
    纯水陆零阅读 300评论 0 11
  • 信用卡申请虽说简单易操作,但能否通过顺利通过审核就要另当别论了,银行对资金的把关相当慎重,若不能及时回笼资金,银行...
    水珠钱包阅读 525评论 0 0
  • 姓名:徐芳芳 公司:南京凯弘进出口贸易有限公司 349期努力二组【日精进打卡第279天】 【知~学习】 《六项精进...
    云海沐晨阅读 151评论 0 0