粥里有勺糖

vuePress-theme-reco 粥里有勺糖    2018 - 2023
粥里有勺糖 粥里有勺糖

Choose mode

  • dark
  • auto
  • light
关于我
备战春秋
  • 心得总结
  • 校招考点汇总
  • 面经汇总
  • 复习自查
技术笔记
  • 技术教程
  • 模板工程
  • 源码学习
  • 技术概念
  • 个人作品
  • 学习笔记
计算机基础
  • 算法与数据结构
  • 操作系统
  • 计算机网络
  • 设计模式
  • 剑指offer
大前端
  • javascript
  • vue
  • html
  • css
  • 🌏浏览器专题
  • Web性能优化
  • regexp
  • node
面试
  • 问解
  • javascript
  • css
  • 手撕代码
  • 性能优化
  • 综合问题
  • 面经汇总
  • 小程序
手撕代码
  • 数据结构与算法
  • javascript
  • css
个人站点
  • GitHub (opens new window)
  • 博客园 (opens new window)
  • 掘金 (opens new window)
线上作品
  • 轻取(文件收集) (opens new window)
  • 个人图床 (opens new window)
  • 考勤小程序 (opens new window)
  • 时光恋人 (opens new window)
  • 在线简历生成 (opens new window)
留言板
Github (opens new window)
author-avatar

粥里有勺糖

285

文章

40

标签

关于我
备战春秋
  • 心得总结
  • 校招考点汇总
  • 面经汇总
  • 复习自查
技术笔记
  • 技术教程
  • 模板工程
  • 源码学习
  • 技术概念
  • 个人作品
  • 学习笔记
计算机基础
  • 算法与数据结构
  • 操作系统
  • 计算机网络
  • 设计模式
  • 剑指offer
大前端
  • javascript
  • vue
  • html
  • css
  • 🌏浏览器专题
  • Web性能优化
  • regexp
  • node
面试
  • 问解
  • javascript
  • css
  • 手撕代码
  • 性能优化
  • 综合问题
  • 面经汇总
  • 小程序
手撕代码
  • 数据结构与算法
  • javascript
  • css
个人站点
  • GitHub (opens new window)
  • 博客园 (opens new window)
  • 掘金 (opens new window)
线上作品
  • 轻取(文件收集) (opens new window)
  • 个人图床 (opens new window)
  • 考勤小程序 (opens new window)
  • 时光恋人 (opens new window)
  • 在线简历生成 (opens new window)
留言板
Github (opens new window)
  • Node

    • NodeJS
    • Node侧实现内容压缩(gzip/br/deflate)介绍与实践
    • 使用TS封装操作MongoDB数据库的工具方法
    • 使用Node.js从终端读入内容
    • 实现一个幽灵依赖扫描工具

使用TS封装操作MongoDB数据库的工具方法

vuePress-theme-reco 粥里有勺糖    2018 - 2023

使用TS封装操作MongoDB数据库的工具方法

粥里有勺糖 2021-05-16 大前端node.js

# 使用TS封装操作MongoDB数据库的工具方法

# 前言

在做毕业设计过程中采用了MongoDb存储应用的日志信息,总结了一些CRUD方法与大家分享一下

关于MongoDb的入门教程推荐大家阅读:

菜鸟教程: MongoDB (opens new window)
菜鸟教程: Node.js 连接 MongoDB (opens new window)

# 获取数据库链接

const {
  host, port, user, password, database,
} = mongodbConfig
const url = `mongodb://${user}:${password}@${host}:${port}/${database}`

// 如果没有设置账号与密码,可以省略
// const url = `mongodb://${host}:${port}/${database}`

interface Res {
    db: MongoClient
    Db: Db
}

function getDBConnection(): Promise<Res> {
  return new Promise((res, rej) => {
    MongoClient.connect(url, {
      useUnifiedTopology: true,
      useNewUrlParser: true,
    }).then((db) => {
      res({
        db,
        Db: db.db(database),
      })
    }).catch((err) => {
      rej(err)
    })
  })
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

使用Promise对其进行包装,返回db(连接实例)与DB(数据库实例)

# 包装数据库查询方法

// 传入的回调函数类型定义
type Callback<T> = (db: Db, resolve: (value: T | PromiseLike<T>) => void) => void

export function query<T>(callback: Callback<T>): Promise<T> {
  const p = new Promise<T>((resolve, rej) => {
    getDBConnection().then(({ db, Db }) => {
      // 执行回调
      callback(Db, resolve)
      // resolve后关闭
      p.catch((e) => rej(e))
        .finally(() => {
          db.close()
        })
    })
  })
  return p
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

获取到链接实例,由调用方传入需要执行的回调函数,在执行resolve后自动通过finally中的回调断开数据库的链接

# CRUD

# 插入数据

function insertCollection<T>(collection: string, data: T[] | T, many = false){
    return mongoDbQuery<InsertOneWriteOpResult<WithId<T>>>((db, resolve) => {
        if (many && Array.isArray(data)) {
            db.collection<T>(collection).insertMany(data as any).then(resolve as any)
            return
        }
        db.collection<T>(collection).insertOne(data as any).then(resolve)
    })
}
1
2
3
4
5
6
7
8
9

参数:

  1. 目标的数据表名
  2. 待插入的数据
  3. 是否同时插入多个数据

# 查询数据

function findCollection<T>(collection: string, query: FilterQuery<T>){
    return mongoDbQuery<T[]>((db, resolve) => {
        db.collection<T>(collection).find(query).toArray().then((data) => {
            resolve(data)
        })
    })
}
1
2
3
4
5
6
7

参数:

  1. 目标的数据表名
  2. 查询条件

# 更新数据

function updateCollection<T>(collection: string, query: FilterQuery<T>, data: UpdateQuery<T> | Partial<T>, many = false){
    return mongoDbQuery<UpdateWriteOpResult>((db, resolve) => {
        if (many) {
            db.collection<T>(collection).updateMany(query, data).then(resolve)
            return
        }
        db.collection<T>(collection).updateOne(query, data).then(resolve)
    })
}
1
2
3
4
5
6
7
8
9

参数:

  1. 目标的数据表名
  2. 查询条件
  3. 新的数据
  4. 是否批量更新

# 删除数据

function deleteCollection<T>(collection: string, query: FilterQuery<T>, many = false) {
    return mongoDbQuery<DeleteWriteOpResultObject>((db, resolve) => {
        if (many) {
            db.collection(collection).deleteMany(query).then(resolve)
            return
        }
        db.collection(collection).deleteOne(query).then(resolve)
    })
}
1
2
3
4
5
6
7
8
9

# 业务调用示例

方法封装好后,业务调用就很简单明了与语义化了,跟直接在mongoDB Shell中写指令一样顺手

function addUser(userId: string, options = {}) {
  const defaultOptions = {
    nickname: '随机',
    gender: Gender.MALE,
    lastLogin: new Date(),
    loginCount: 0,
    avatar: '/static/logo.png',
  }
  const ops = Object.assign(defaultOptions, options)
  return insertCollection('user', { userId, ...ops })
}

function findUser(user:User) {
  return findCollection<User>('user', user)
}

function updateUserInfo(userId: string, info: User) {
    return updateCollection<User>('user', {
        userId,
    }, {
        $set: info,
    })
}

function deleteUser(userId: number) {
    return deleteCollection<User>('user', { id: userId })
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# 最后

完整源码地址移步这里 (opens new window)

Edit this page (opens new window)
Last Updated: 2022/5/15 12:46:34