封装Mongodb数据库 在NodeJs中操作数据库(增删改查)

MongoDB:

数据库:简单理解为存储数据的仓库。世界上有各种各样的数据库应用程序。大致可分为两类:

  SQL数据库(关系型数据库): mySql、oracle、sqlserver等

  NoSql数据库(非关系型数据库):Mongodb数据库等

SQL数据库:

结构化查询语言:structure query language

它的结构组成:应用程序 => 数据库 => 表 => 数据。使用SQL数据库要学习SQL语言。

NoSql数据库

它的结构组成:应用程序 => 数据库 => 集合 => 文档。

SQL与NOSQL的最大区别在于NoSQL的集合中的文档,它的结构可以不固定。

开启数据库mongodb数据库:

  可以通过提供的mongod指令开启

  默认开启的是:c:/data/db (没有该目录需创建 data/db)

  默认端口号: 27017

开启指定的数据库:

  可以输入 mongod --dbpath 目标数据库

    例如: mongod --dbpath c:/aaa

数据库操作:

  mongo指令  连接一个已经开启的数据库

开启多个数据库

  当我们需要开启多个数据库的时候。此时,需要指定新的端口号

  例如:mongod --dbpath c:/aaa --port 27018

连接指定的数据库

  当需要连接指定的数据库的时候。此时, 需要输入其它指令:

  例如: mongo --port 27018

 

mongodb常用指令:

  查看数据库:show dbs

  创建/切换数据库:use dbName

  查看集合:show collections

  添加数据:db[collectionName].insert({})

    以上一个指令,做了两件事件:1 创建了一个use集合 2 插入了一条数据

  查看集合中数据:db[collectionName].find()

  查看所在数据库:db

  删除数据:db[collectionName].deleteOne()

  清空数据:db[collectionName].remove()

  修改数据:db[collectionName].update(query, updated, options)

  query: 查询条件

  uptated: 修改成为的数据

  options: 是配置项 决定是否修改多项数据

    当修改之后,发现数据丢失了,如果只是想要修改数据中的某一个字段的时候

    提供了$set修改器,允许我们只对其中的某一个字段修改

  删除指定的集合:db[collectionName].drop()

  删除指定的数据库:db.dropDatabase()

NodeJS 中操作数据库:

  nodejs与Mongodb都是单独的应用程序 

  通过nodejs操作mongodb数据库 需要借助模块: mongodb

封装Mongodb数据库 在NodeJs中操作数据库(增删改查) 代码如下

// 引入mongodb模块
let { MongoClient, ObjectId } = require('mongodb');

// 定义数据库类
function DataBase(url, databaseName, collectionName) {
    // 存储信息
    this.url = url;
    this.databaseName = databaseName;
    // 集合名称
    this.collectionName = collectionName;
}
// 定义原型方法
Object.assign(DataBase.prototype, {
    // 切换集合名称的方法
    collection(name) {
        this.collectionName = name;
        // 链式调用
        return this;
    },

    // 定义connect方法,可以连接数据库,并返回数据库对象
    connect() {
        return new Promise((resolve, reject) => {
            // 连接数据库
            MongoClient.connect(this.url, {useNewUrlParser: true}, (err, client) => {
                // 有错误表示连接失败
                if(err) {
                    reject(err);
                } else {
                    // 返回数据库对象
                    resolve({ database: client.db(this.databaseName), client})
                }
            })
        })
    },
    
  
    // 插入一条数据,返回promise对象
    insertOne(name, data) {
        return new Promise((resolve, reject) => {
            // 直接连接数据库
            this.connect()
                // 成功
                .then(({database, client}) => {
                    database.collection(name).insertOne(data, (err, res) => {
                        // console.log(err, res);
                        // 如果有错误
                        if(err) {
                            reject({errno: 2, err});
                        } else if(res.result.n > 0) {
                            // 写入数据成功
                            resolve();
                        } else {
                            reject({errno: 3, err: '没有写入数据'})
                        }

                        // 关闭数据库
                        client.close();
                    })
                })
                // 连接数据库失败
                .catch(err => reject({errno: 1, err}))
        })
    },

    // 插入多条数据
    insertMany(arr) {
        // 返回promise
        return new Promise((resolve, reject) => {
            // 1 连接数据库, 2获取集合,3 通过集合插入数据
            this.connect()
                // 监听成功
                .then(({database, client}) => {
                    // 获取集合
                    database.collection(this.collectionName)
                        // 插入多条数据
                        .insertMany(arr, (err, data) => {
                            // 有错误
                            if(err) {
                                reject({errno: 2, err})
                            } else if(data.result.n > 0) {
                                // 成功了
                                resolve()
                            } else {
                                // 没有插入数据
                                reject({ errno: 3, err: '没有插入数据' })
                            }
                        })
                    // 关闭数据库
                    client.close();
                })
                // 监听失败
                .catch(err => reject({ errno: 1, err }))
        })
    },

    // 删除一条数据
    deleteOne(obj) {
        return new Promise((resolve, reject) => {
            // 1 连接数据库, 2 连接集合    3 删除
            this.connect()
                // 成功
                .then(({database, client}) => {
                    // 如果是根据_id进行删除的,要通过ObjectId方法包装
                    if(obj._id) {
                        obj._id = ObjectId(obj._id);
                    }
                    // 通过数据库,获取集合
                    database.collection(this.collectionName)
                        // 删除
                        .deleteOne(obj, (err, data) => {
                            // console.log(err, data);
                            // 有错误
                            if (err) {
                                reject({ errno: 2, err })
                            } else if (data.result.n > 0) {
                                // 成功
                                resolve();
                            } else {
                                // 没有删除任何一条数据
                                reject({ errno: 3, err: '没有删除数据' })
                            }
                        })
                    // 关闭数据库
                    client.close();
                })
                // 失败
                .catch(err => reject({ errno: 1, err }))
        })
    },

    // 删除多条数据
    deleteMany(arr) {
        // 遍历数组,对每一个成员,执行deleteOne
        return Promise.all(arr.map(item => this.deleteOne(item)))
    },

    // 修改一条数据
    updateOne(oldObj, newObj) {
        return new Promise((resolve, reject) => {
            // 连接数据库
            this.connect()
                // 成功
                .then(({ database, client }) => {
                    // 如果传递了_id要包装
                    if (oldObj._id) {
                        oldObj._id = ObjectId(oldObj._id)
                    }
                    // 获取集合,更新数据
                    database.collection(this.collectionName)
                        // 更新数据
                        .updateOne(oldObj, newObj, (err, data) => {
                            // console.log(err, data);
                            // 判断错误
                            if (err) {
                                reject({ errno: 2, err })
                            } else if (data.result.n > 0) {
                                // 成功
                                resolve();
                            } else {
                                reject({ errno: 3, err: '没有更新数据' })
                            }
                        })
                    // 关闭数据库
                    client.close();
                })
                // 失败
                .catch(err => reject({ errno: 1, err }))
        })
    },

    // 修改多条数据
    updateMany(arr) { 
        // 对每一个成员进行单独更新,并监听结果
        // 数组中的每一个成员,分别传递给函数,作为参数,用...语法
        return Promise.all(arr.map(item => this.updateOne(...item)))
    },

    // 查询一条数据
    findOne(obj) {
        return new Promise((resolve, reject) => {
            // 连接数据库
            this.connect()
                // 成功
                .then(({database, client}) => {
                    // 如果传递了_id要包装
                    if (obj._id) {
                        obj._id = ObjectId(obj._id)
                    }
                    // 查询数据
                    database.collection(this.collectionName)
                        .findOne(obj, (err, data) => {
                            // 有错误
                            if (err) {
                                reject({ errno: 2, err })
                            } else if (data) {
                                // 找到数据了
                                resolve(data);
                            } else {
                                // 没有数据
                                reject({ errno: 3, err: '没有找到数据' })
                            }
                        })
                        // 关闭数据库
                        client.close();
                })
                // 失败
                .catch(err => reject({ errno: 1, err }))
        })
    },

    // 查询多条数据
    findMany(obj, fn = data => data) {
        return new Promise((resolve, reject) => {
            // 连接数据库
            this.connect()
                // 成功
                .then(({database, client}) => {
                    // 如果传递了_id要包装
                    if (obj._id) {
                        obj._id = ObjectId(obj._id)
                    }
                    fn(database.collection(this.collectionName).find(obj))
                        // .sort({n: 1}) // 升序
                        // .sort({n: -1}) // 降序
                        // .skip(3) // 跳过
                        // .limit(1) // 截取
                        .toArray((err, data) => {
                             // 判断
                             if (err) {
                                reject({ errno: 2, err })
                            } else if (data.length) {
                                // 成功
                                resolve(data)
                            } else {
                                // 失败
                                reject({ errno: 3, err: '没有找到数据' })
                            }
                        })
                        // 关闭数据库
                        client.close();
                })
                // 失败
                .catch(err => reject({ errno: 1, err }))
        })
    }
})


// 通过实例化,创建一个数据库
let db = new DataBase('mongodb://localhost:27017', 'hello', 'demo');

// 通过db对象,来操作数据库
// 增删改查

// 插入一条数据
// db.insertOne('demo', {num: 111})
//     .then(res => {console.log('插入成功')})

// 插入多条数据
// db.collection('demo')
//     .insertMany([{ num: 222 }, { num: 333 }, { num: 444 }])
//     .then(res => console.log('插入多条数据成功'))

// 删除一条数据
// db.collection('demo')
//     // .deleteOne({num: 444})
//     .deleteOne({_id: "5efd6890869a612a98107d43"})
//     .then(res => console.log('删除一条数据成功'))
//     .catch(err => console.log(err));

// 删除多条数据
// db.collection('demo')
//     .deleteMany([{ num: 222 }, { num: 333 }, { num: 444 }])
//     .then(res => console.log('删除多条数据成功'))
//     .catch(err => console.log(err));

// 修改一条数据
// db.collection('demo')
//     .updateOne({num: 222}, {$set: {num: 666}})
//     .updateOne({_id: '5efd699483e2df3e8469c9ba'}, {$set: {num: 888}})
//     .then(res => console.log('修改一条数据成功'))

// 修改多条数据
// db.collection('demo')
//     .updateMany([
//         [{_id: '5efd699483e2df3e8469c9ba'}, {$set: {num: 444}}],
//         [{num: 666}, {$set: {num: 222}}],
//         [{num: 333}, {$set: {num: 555}}]
//     ])
//     .then(res => console.log('修改多条数据成功'))

// 查询一条数据
// db.findOne({num: 555})
// db.findOne({_id: '5efd699483e2df3e8469c9ba'})
//     .then(res => console.log('查询一条数据成功', res))
//     .catch(err => console.log(err))

// 查询多条数据
db.findMany({ num: 999 }, function(data) {
    // 设置限制条件
    // return data.sort({ n: 1 })
    return data.sort({ n: -1 })
    // return data.sort({ n: -1 }).skip(1).limit(1)
})
    .then(res => console.log('查询成功', res))
    .catch(err => console.log(err))
原文地址:https://www.cnblogs.com/yess/p/13227634.html