美文网首页
NodeJS 对 MongoDB 封装

NodeJS 对 MongoDB 封装

作者: Geeker工作坊 | 来源:发表于2020-02-16 21:47 被阅读0次

开始之前

按照 MongoDB Node.JS Driver 我们每次使用JS对数据进行操作都需要先建立连接,如果我们每次操作都要重新建立一次连接必然会很消耗性能(建立连接时长大约一秒钟),为了减少性能的损耗同时使我们用 nodejs 操作 MongoDB 更加灵活方便,按照官方文档封装一个了 DB 模块。

原生 JS 中静态方法、类、继承

function Persion(name,age){
  /* 构造函数里面的方法和属性 */
  this.name = name;
  this.age = age;
  this.printInfo = function(){
    console.log(`${this.name}---${this.age}`)
  }
}

/* 原型链上的属性和方法和可以被多个实例共享 */
Person.prototype.sex = 'man';
Persion.prototype.work = function(){
  console.log(`${this.name}--${this.age}--${this.work}`)
}

/* 静态方法 我们直接在方法名上添加就可以使用方法方法名调用 */
Person.staticMethod = function(){
  console.log('这是一个静态方法')
}

/* 实例方法是通过实例化来调用,静态方法是通过类名调用 */
let p = new Person('zhangsan', '18');
p.printInfo();  // zhangsan--18
p.work(); // zhangsan--18--man
Person.staticMethod(); // 这是一个静态方法

ES5中的继承

/* 
 *  ES5中的继承可用使用原型链继承和对象冒充的方式来实行
 *  对象冒充继承:没法继承原型链上的属性和方法
 *  原型链继承:可以继承构造函数以及原型链上面的属性和方法,但实例化子类时没法传参数给父类
 *  将这两者结合起来,更多的方法请查看 《JavaScript高级程序设计》 第六章
*/

function Person(name,age){
  this.name = name;
  this.age = age;
  this.printInfo = function(){
     console.log(`${this.name}--${this.age}`);
  }
}

Person.prototype.work = function(){
  console.log('work')
}

function Employee(name,age){
  Person.call(this,name,age) // 对象冒充实现继承
}

Employee.prototype = new Person();

let emp = new Employee('zhangsan', 18);

emp.printInfo(); // zhangsan--18

emp.work(); // work

ES6 中类、静态方法、继承

class Person{
  constructor(name,age){
    this._name = name;
    this._age = age;
  }
  getName(){
    console.log(this._name);
  }
  setName(name){
    this._name = name;
  }
}

/* ES6 中的继承 使用 extends 关键字  静态方法使用 static 关键字*/
class Employee extends Person{
  constructor(name,age,sex){
    super(name,age);
    this._sex = sex;
  }
  static staticMethod(){
    console.log('这是一个静态方法');
  }
  printInfo(){
    console.log(`${this._name}--${this._age}--${this._sex}`);
  }
}
let emp = new Employee('zhangsan', '18', 'man');
emp.getName(); // zhangsan
emp.printInfo(); // zhangsan--18--man
Employee.staticMethod(); //这是一个静态方法

ES6单例模式

class Db {
    static getInstance(){   /*单例*/
        if(!Db.instance){
            Db.instance=new Db();
        }
        return Db.instance;
    }
    constructor(){
        console.log('实例化会触发构造函数');
        this.connect();
    }
    connect(){
        console.log('连接数据库');
    }
    find(){
        console.log('查询数据库');
    }
}
var myDb=Db.getInstance(); // 实例化会触发构造函数 连接数据库
var myDb2=Db.getInstance(); 
var myDb3=Db.getInstance();
var myDb4=Db.getInstance();
myDb3.find(); //查询数据库
myDb4.find(); //查询数据库

NodeJS 对 MongoDB的封装

const MongoDB = require('mongodb');
const MongoClient = MongoDB.MongoClient;
const ObjectID = MongoDB.ObjectID;
const CONFIG = {
    dbUrl: 'mongodb://127.0.0.1:27017/',
    dbName: 'test'
};

class DB{
    static getInstance(){
        if(!DB.instance){
            DB.instance = new DB();
        }
        return DB.instance;
    }
    constructor() {
        this.dbClient = '';
        this.connect();
    }
    connect(){
        let self = this;
        return new Promise(((resolve, reject) => {
            if(!self.dbClient){
                MongoClient.connect(CONFIG.dbUrl,{'useNewUrlParser': true, 'useUnifiedTopology':true},(err,client)=>{
                    if(err){
                        reject(err);
                    }else{
                        self.dbClient = client.db(CONFIG.dbName);
                        resolve(self.dbClient);
                    }
                })
            }else{
                resolve(self.dbClient);
            }
        }))
    }
    insertDocuments(collectionName,jsonArr){
        if(!collectionName || !jsonArr || !(jsonArr instanceof Array)) throw '参数错误';
        return new Promise((resolve, reject) => {
            this.connect().then(db=>{
                const collect = db.collection(collectionName);
                collect.insertMany(jsonArr,(err,result)=>{
                    if(!err){
                        resolve(result);
                    }else{
                        reject(err);
                    }
                })
            })
        })
    }
    findDocuments(collectionName,json){
        if(!collectionName || !json ) throw '参数错误';
        return new Promise((resolve, reject) => {
            this.connect().then(db=>{
                let result = db.collection(collectionName).find(json);
                result.toArray((err,data)=>{
                    if(!err){
                        resolve(data);
                    }else{
                        reject(err);
                    }
                })
            })
        })
    }
    removeDocument(collectionName,json){
        if(!collectionName || !json ) throw '参数错误';
        return new Promise(((resolve, reject) => {
            this.connect().then(db=>{
                const collection = db.collection(collectionName);
                collection.deleteOne(json,(err,result)=>{
                    if(!err){
                        resolve(result);
                    }else{
                        reject(err);
                    }
                })
            })
        }))
    }
    updateDocument(collectionName,filter,json){
        if(!collectionName || !filter || !json) throw '参数错误';
        return new Promise((resolve, reject) => {
            this.connect().then(db=>{
                const collection = db.collection(collectionName);
                collection.updateOne(filter,{$set:json},(err,result)=>{
                    if(!err){
                        resolve(result)
                    }else{
                        reject(err)
                    }
                })
            })
        })
    }
    getObjectId(id){    /*mongodb里面查询 _id 把字符串转换成对象*/
        return new ObjectID(id);
    }
}

module.exports = DB.getInstance();

相关文章

网友评论

      本文标题:NodeJS 对 MongoDB 封装

      本文链接:https://www.haomeiwen.com/subject/ohzmfhtx.html