node.js连mongdb封装[增删改查]

var MongoClient = require('mongodb').MongoClient;

class DAO {
    constructor(url, dbName, collectionName) {
        this.url = url;
        this.dbName = dbName;
        this.collectionName = collectionName;
    }
    _connect() {
        return new Promise((resolve, reject) => {
            MongoClient.connect(this.url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => { //client参数就是连接成功之后的mongoclient
                if (err) return reject(err);
                resolve(client)
            })
        })
    }

    //插入
    //doucument 要插入的数据 arr||obj
    //insertMany 是否插入多条 boolean
    insert(documents, insertMany) {
        return new Promise((resolve, reject) => {
            this._connect().then((client) => {
                let db = client.db(this.dbName); //调用test数据库
                if (insertMany) {
                    db.collection(this.collectionName).insertMany(documents).then((res) => { //user表插入多条
                        resolve(res)
                        client.close()
                    })
                    return
                }
                db.collection(this.collectionName).insertOne(documents).then((res) => { //user表插入单条
                    resolve(res);
                    client.close();
                })
            })
        })
    }

    //查询
    query(document, pageConfig) {
        document = document || {}; //查找的对象,空就查找全部
        pageConfig = pageConfig || { amount: 0, page: 0 } //amount条数,page页数
        let resData = []; //存放查找到的数据

        return new Promise((resolve, reject) => { //返回一个Promise
            this._connect().then((client) => { //调用构造函数连接数据库服务器
                let db = client.db(this.dbName); //调用test数据库
                let cursor = db.collection(this.collectionName).find(document).limit(pageConfig.amount).skip(pageConfig.amount * (pageConfig.page - 1)); //查找
                cursor.each((err, data) => {
                    if (err) return reject(err);
                    if (data != null) { //数据不为空就放入数组里
                        resData.push(data)
                    } else {
                        resolve(resData);
                        client.close();
                    }
                })
            })
        })
    }

    //删除
    del(query, deleteMany) {
        return new Promise((resolve, reject) => {
            this._connect().then(client => { //连接mongodb服务
                let db = client.db(this.dbName); //连接test数据库
                if (deleteMany) {
                    db.collection(this.collectionName).deleteMany(query).then(res => {
                        resolve(res);
                        client.close()
                    })
                    return;
                }
                db.collection(this.collectionName).deleteOne(query).then(res => {
                    resolve(res);
                    client.close()
                })
            })
        })
    }

    //修改
    update(filter, updater) {
        return new Promise((resolve, reject) => {
            this._connect().then(client => {
                let updaterCpy = { $set: updater };
                let db = client.db(this.dbName); //连接test数据库
                db.collection(this.collectionName).updateMany(filter, updaterCpy).then(res => {
                    resolve(res);
                    client.close()
                })
            })
        })
    }

}

let dao = new DAO('mongodb://localhost:27017/', 'test', 'user')

新增一条数据

let obj = { hello: 'world' }
dao.insert(obj).then((res) => {})

新增多条数据

let arr = [];
for (let i = 0; i < 10; i++) {
    arr.push({
        userid: '123',
        age: i
    })
}
dao.insert(arr, true).then((res) => {})

查询数据

dao.query({ userid: '123' }).then((res) => {
    for (let i = 0; i < res.length; i++) {
        console.log(res[i])
    }
})

调用查+分页

let document = ({ userid: '123' })
let pageConfig = { amount: 10, page: 2 }
dao.query(document, pageConfig).then(res => {
    console.log(JSON.stringify(res))
})

删除一条数据

dao.del({ userid: '123' }).then(res => {})

删除多条数据

dao.del({ userid: '123' }, true).then(res => {})

修改数据

let filter = { hello: 'mongo' }
let update = { hello: 'node', age: 45 }
dao.update(filter, update).then(res => {})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值