nodejs--封裝Mongodb驅動代碼

 公司項目最近在升級mongodb版本和mongodb驅動,因爲項目開發時沒有封裝mongodb驅動的代碼,導致升級後增刪改查都需要修改,爲了偷懶,在基於mongodb驅動代碼上進行封裝,在方法上兼容mongodb驅動2.x版本的調用方式,避免整個項目進行改造,節省了幾天的時間!!!如果你有心思,可以在下面的代碼裏面做一下處理,就同時就兼容2.x和3.x版本的mongdoDB驅動了

class CollectionBase {
    constructor(clientObj,collectionName) {
        this.runMongoClient = clientObj;//初始化mongodb表操作對象
        this.collectionName = collectionName;//定義表名
        this.collectionObject = this.runMongoClient.collection(this.collectionName);
    }

    /**
     * 插入單條文檔
     * 說明:
     * 對mongodb驅動3.x以上的版本推薦使用
     * 修改時間:2019-12-03
     * @returns {Promise<void>}
     */
    async insertOne() {//繼承新的insertMany操作命令
        return await this.collectionObject.insertOne.apply(this.collectionObject,arguments);
    }

    /**
     * 插入多條文檔
     * 說明:
     * 對mongodb驅動3.x以上的版本推薦使用
     * 修改時間:2019-12-03
     * @returns {Promise<void>}
     */
    async insertMany(){//插入多條
        return await this.collectionObject.insertMany.apply(this.collectionObject,arguments);
    }

    /**
     * 插入(單條/多條)文檔
     * 說明:
     * 對mongodb驅動2.x版本進行兼容,對傳入的參數進行判斷調用多條文檔插入還是單條文檔插入
     * 修改時間:2019-12-03
     * @returns {Promise<void>}
     */
    async insert(){
        if(Array.isArray(arguments[0])){
            return await this.insertMany.apply(this,arguments);
        }else{
            return await this.insertOne.apply(this,arguments);
        }
    }

    /**
     * 更新多條文檔
     * 說明:
     * mongodb驅動3.x以上版本推薦使用
     * 修改時間:2019-12-03
     * @returns {Promise<*>}
     */
    async updateMany(){
        // console.log("updateMany()");
        return await this.collectionObject.updateMany.apply(this.collectionObject,arguments);
    }

    /**
     * 更新單條文檔
     * 說明:
     * mongodb驅動3.x以上版本推薦使用
     * 修改時間:2019-12-03
     * @returns {Promise<*>}
     */
    async updateOne(){
        // console.log("updateOne()");
        return await this.collectionObject.updateOne.apply(this.collectionObject,arguments);
    }

    /**
     * 更新(單條/多條)文檔
     * 說明:
     * 兼容mongodb驅動2.x版本,根據options的multi是否等於true決定是否更新多條還是單條文檔
     * 修改時間:2019-12-03
     * @returns {Promise<*>}
     */
    async update(){
        if (!!arguments[2] && arguments[2].multi == true){
            return await this.updateMany.apply(this,arguments);
        } else{
            return await this.updateOne.apply(this,arguments);
        }
    }

    /**
     * 查詢多條文檔
     * 說明:
     * 兼容mongodb驅動2.x版的寫法,自動補充projection關鍵字
     * 修改時間:2019-12-03
     * @returns {Promise<*>}
     */
    find(){
        if(!!arguments[1] && !arguments[1].projection){
            arguments[1] = {projection:arguments[1]};
        }
        // console.log("find()-->arguments:",arguments);
        return this.collectionObject.find.apply(this.collectionObject,arguments);
    }

    /**
     * 查詢單條文檔
     * 說明:
     * 兼容mongodb驅動2.x版的寫法,自動補充projection關鍵字
     * 修改時間:2019-12-03
     * @returns {Promise<*>}
     */
    findOne(){
        if(!!arguments[1] && !arguments[1].projection){
            arguments[1] = {projection:arguments[1]};
        }
        // console.log("this.collectionName:",this.collectionName);
        // console.log("findOne()-->arguments:",arguments);
        return this.collectionObject.findOne.apply(this.collectionObject,arguments);
    }

    /**
     * 刪除單條文檔
     * 說明:刪除單條文檔推薦使用這個方法,不推薦使用remove
     * 修改時間:2019-12-03
     * @returns {Promise<*>}
     */
    async deleteOne(){
        return await this.collectionObject.deleteOne.apply(this.collectionObject,arguments);
    }

    /**
     * 刪除多條文檔
     * 說明:刪除多天文檔推薦使用這個方法,不推薦使用remove
     * 修改時間:2019-12-03
     * @returns {Promise<*>}
     */
    async deleteMany(){
        return await this.collectionObject.deleteMany.apply(this.collectionObject,arguments);
    }

    /**
     * 刪除文檔
     * 說明:爲了兼容2.x版本的寫法,默認刪除符合條件所有文檔
     * 修改時間:2019-12-03
     * @returns {Promise<*>}
     */
    async remove(){
        return await this.deleteMany.apply(this,arguments);
    }

    /**
     * 聚合查詢
     * 說明:
     * 修改時間:2019-12-03
     * @returns {Promise<*>}
     */
    aggregate(){
        return this.collectionObject.aggregate.apply(this.collectionObject,arguments);
    }

    /**
     * 去重
     * @returns {*}
     */
    distinct(){
        return this.collectionObject.distinct.apply(this.collectionObject,arguments);
    }

    // /**
    //  * 返回事務會話
    //  * @returns {*}
    //  */
    // startSession(){
    //     return this.runMongoClient.startSession();
    // }
}

class MongodbBase {
    constructor(clientObj) {
        this.runMongoClient = clientObj;//初始化mongodb表操作對象
        this.databaseName = clientObj.databaseName;
    }

    collection(collectionName) {
        return new CollectionBase(this.runMongoClient,collectionName);
    }
}

module.exports = MongodbBase;

 調用方式如下:

var MongodbBase = require('./MongodbBase');
var mongo = require('mongodb'),MongoClient = mongo.MongoClient;
var mongoUrl = 'mongodb://test:[email protected]:27017/test?replicaSet=mgset-17098013&readPreference=secondaryPreferred';

MongoClient.connect(mongoUrl,{ useNewUrlParser: true,useUnifiedTopology: true },async function(err,client){
    if(!err){
        var client = new MongodbBase(client.db());
        console.log(client.databaseName);
        var coll_member = client.collection("member");
        console.log(coll_member.collectionName);
        var result =await coll_member.find({},{_id:0});               //2.x驅動的寫法
        //var result =await coll_member.find({},{projection:{_id:0}});    //3.x驅動的寫法
        console.log(result);
    }else{
        console.error("mongodb鏈接超時:",mongoUrl)
    }
});

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章