Koa(三、mongodb工具类,以及导入导出)

  • 首先安装mongodb的驱动
  • API地址:http://mongodb.github.io/node-mongodb-native/3.0/quick-start/quick-start/
工具类db.js:
/**

 * http://mongodb.github.io/node-mongodb-native

 * http://mongodb.github.io/node-mongodb-native/3.0/api/
 */

const { MongoClient, ObjectID } = require('mongodb');
let Config = require('./config.js');
const client = new MongoClient(Config.dbUrl, { useNewUrlParser: true });

class Db {
    static getInstance() {
        if (!Db.instance) {
            Db.instance = new Db();
        }
        return Db.instance;
    }

    constructor() {

        this.dbClient = '';
        this.connect();
    }

    connect() {
        let _that = this;
        return new Promise((resolve, reject) => {
            if (!_that.dbClient) {
                client.connect((err, client) => {
                    if (err) {
                        reject(err)
                    } else {
                        _that.dbClient = client.db(Config.dbName);
                        resolve(_that.dbClient)
                    }
                })

            } else {
                resolve(_that.dbClient);
            }
        })

    }
    /*
    
         DB.find('user',{})  返回所有数据
    
         DB.find('user',{},{"title":1})    返回所有数据  只返回一列(此时返回指定列,title)
         DB.find('user',{},{"title":1},{   返回第二页的数据   分页使用
            page:2,
            pageSize:20,
            sort:{"add_time":-1}
         })
         js中实参和形参可以不一样      arguments 对象接收实参传过来的数据
    
        * */
    find(collectionName, json1, json2, json3) {
        let sortJson = {};
        if (arguments.length == 2) {
            var attr = {};
            var slipNum = 0;
            var pageSize = 0;

        } else if (arguments.length == 3) {
            var attr = json2;
            var slipNum = 0;
            var pageSize = 0;
        } else if (arguments.length == 4) {
            var attr = json2;
            var page = json3.page || 1;
            var pageSize = json3.pageSize || 20;
            var slipNum = (page - 1) * pageSize;
            if (json3.sortJson) {
                sortJson = json3.sortJson;
            }
        } else {
            console.log('传入参数错误')
        }

        return new Promise((resolve, reject) => {
            this.connect().then((db) => {
                var result = db.collection(collectionName).find(json1, attr).skip(slipNum).limit(pageSize).sort(sortJson);
                result.toArray(function (err, docs) {

                    if (err) {
                        reject(err);
                        return;
                    }
                    resolve(docs);
                })

            })
        })
    }
    update(collectionName, json1, json2) {
        return new Promise((resolve, reject) => {
            this.connect().then((db) => {
                //db.user.update({},{$set:{}})
                db.collection(collectionName).updateOne(json1, {
                    $set: json2
                }, (err, result) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                })

            })

        })

    }
    insert(collectionName, json) {
        return new Promise((resolve, reject) => {
            this.connect().then((db) => {

                db.collection(collectionName).insertOne(json, function (err, result) {
                    if (err) {
                        reject(err);
                    } else {

                        resolve(result);
                    }
                })


            })
        })
    }

    remove(collectionName, json) {

        return new Promise((resolve, reject) => {
            this.connect().then((db) => {

                db.collection(collectionName).removeOne(json, function (err, result) {
                    if (err) {
                        reject(err);
                    } else {

                        resolve(result);
                    }
                })


            })
        })
    }
    getObjectId(id) {
        return new ObjectID(id);
    }
    //统计数量的方法
    count(collectionName, json) {
        return new Promise((resolve, reject) => {
            this.connect().then((db) => {
                let result = db.collection(collectionName).countDocuments(json);
                result.then(function (count) {
                    resolve(count);
                }
                )
            })
        })
    }
}
module.exports = Db.getInstance();
配置文件config.js
//配置文件
let app={
    url:'mongodb://localhost:27017',
    dbName:'Demo'
}
module.exports=app;

//或者
const app={
    dbUrl: 'mongodb://admin:123456@localhost:27017/',
    dbName: 'koa'
}
module.exports=app;

导入以及导出

在 Mongodb 中我们使用 mongodump 命令来备份 MongoDB 数据。该命令可以导出所有数据
到指定目录中。mongodump 命令可以通过参数指定导出的数据量级转存的服务器。使用
mongorestore 命令来恢复备份的数据。

  • 导出

mongodump -h dbhost -d dbname -o dbdirectory

  • 导入

mongorestore -h dbhost -d dbname path

注意如果开启了用户权限则如下:(导入也类似)

mongorestore -h 127.0.0.1 -u admin -p 123456 -d koa C:\Users\Administrator\Desktop\koa_database --authenticationDatabase admin

  • authenticationDatabase admin:代表该命令的等级,不然无法导入
TIM截图20190412105205.png

你可能感兴趣的:(Koa(三、mongodb工具类,以及导入导出))