nodejs--封装Mongodb驱动代码

2 篇文章 0 订阅
1 篇文章 0 订阅

 公司项目最近在升级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:123456@127.0.0.1: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)
    }
});

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值