惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
C
Cybersecurity and Infrastructure Security Agency CISA
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tailwind CSS Blog
G
GRAHAM CLULEY
博客园 - 叶小钗
T
Threatpost
小众软件
小众软件
The Hacker News
The Hacker News
博客园 - 聂微东
博客园 - 三生石上(FineUI控件)
P
Privacy & Cybersecurity Law Blog
AWS News Blog
AWS News Blog
P
Proofpoint News Feed
Jina AI
Jina AI
S
Schneier on Security
N
News | PayPal Newsroom
Help Net Security
Help Net Security
A
Arctic Wolf
T
The Blog of Author Tim Ferriss
大猫的无限游戏
大猫的无限游戏
T
Troy Hunt's Blog
美团技术团队
L
Lohrmann on Cybersecurity
The Last Watchdog
The Last Watchdog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
P
Privacy International News Feed
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
B
Blog RSS Feed
The Register - Security
The Register - Security
博客园 - Franky
Stack Overflow Blog
Stack Overflow Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
S
SegmentFault 最新的问题
腾讯CDC
云风的 BLOG
云风的 BLOG
Simon Willison's Weblog
Simon Willison's Weblog
Google DeepMind News
Google DeepMind News
AI
AI
GbyAI
GbyAI
Attack and Defense Labs
Attack and Defense Labs
Cloudbric
Cloudbric
I
Intezer
The GitHub Blog
The GitHub Blog
V2EX - 技术
V2EX - 技术
Scott Helme
Scott Helme
J
Java Code Geeks

小陈同学 - 后端

从 requirements.txt 到 pyproject.toml:现代 Python 项目升级实战指南(含依赖分析与 Docker) 用 NumPy 玩转电影评分系统:从随机数据到洞察分析 NumPy 进阶:搞懂广播机制,才能真正玩转数组 NumPy 入门:别再用 for 循环折磨自己了 uv:用 Rust 武装的极速 Python 包管理器入门指南 NodeJs基于Token的身份认证
NodeJs连接MongoDB以及操作方法
Caleb · 2020-07-07 · via 小陈同学 - 后端

用 Node.js 的 mongodb 包封装连接池与增删改查,实现简洁易用的 MongoDB 操作类。

因为业务需要,老板就让我搞了一回 MongoDB。可真是懵逼树上懵逼果,懵逼树下你和我。本着务实求知的态度,研究了下也算是搞完了。开个香槟庆祝下。

准备阶段

安装依赖

这里采用的是 npm 仓库中的 mongodb 包。

npm install mongodb -D

准备目录

在主目录下创建 db 文件夹。并同时在文件夹中创建 connect.js , index.js

├─ db
│  ├─connect.js
│  └─index.js
├─ app.js
├─ ...

连接数据库

connect.js

const MongoClient = require("mongodb").MongoClient;

const config = {
  dstHost: "127.0.0.1",
  dstPort: 42351,
}; // 数据库基本信息

const mydbname = "xxxx"; // 数据库名

function connect() {
  return new Promise((resolve, reject) => {
    // mongodb://127.0.0.1:12345/xxxxxx  连接格式
    MongoClient.connect(
      `mongodb://${config.dstHost}:${config.dstPort}/${mydbname}`,
      {
        useUnifiedTopology: true,
        maxPoolSize: 10,
        minPoolSize: 2,
        poolSize: 10,
      },
      function (dbConnectError, database) {
        if (dbConnectError) {
          console.error("连接失败,原因是:", dbConnectError);
          reject(dbConnectError);
        }
        const dbo = database.db(mydbname);
        console.log("连接成功!");
        resolve(dbo); // 抛出连接实例
      }
    );
  });
}

module.exports = connect;

index.js

const connect = require("./connect");

class DB {
  constructor() {
    this.dbo = "";
    // 连接数据库,获取实例对象
    connect().then((res) => {
      this.dbo = res;
    });
  }
  // 增
  insert(collectionName, data) {
    return new Promise((resolve, reject) => {
      this.dbo.collection(collectionName).insertMany(data, function (error, result) {
        if (error) {
          reject(error);
          throw error;
        }
        resolve(result);
      });
    });
  }
  // 查
  read(collectionName, where, fields, projection, sort, limit, skip) {
    return new Promise((resolve, reject) => {
      this.dbo
        .collection(collectionName)
        .find(where || {}, fields || {})
        .project(projection || {})
        .sort(sort || {})
        .limit(limit || 100)
        .skip(skip || 0)
        .toArray((error, result) => {
          if (error) {
            reject(error);
            throw error;
          }
          resolve(result);
        });
    });
  }
  // 改
  update(collectionName, where, data) {
    return new Promise((resolve, reject) => {
      this.dbo.collection(collectionName).updateMany(where, data, function (error, result) {
        if (error) {
          reject(error);
          throw error;
        }
        resolve(result);
      });
    });
  }
  // 删
  remove(collectionName, where) {
    return new Promise((resolve, reject) => {
      if (where) {
        this.dbo.collection(collectionName).deleteMany(where, function (error, result) {
          if (error) {
            reject(error);
            throw error;
          }
          resolve(result);
        });
      }
    });
  }
  // 总
  count(collectionName) {
    return new Promise((resolve, reject) => {
      try {
        let result = this.dbo.collection(collectionName).countDocuments();
        resolve(result);
      } catch (e) {
        reject(e);
      }
    });
  }
  // 自定义数据库语句
  dbo(callback) {
    return new Promise((resolve, reject) => {
      try {
        let result = null;
        if (typeof callback === "function") {
          result = callback(this.dbo);
        }
        resolve(result);
      } catch (e) {
        reject(e);
      }
    });
  }
}

module.exports = DB;

使用

在某个逻辑中:

const DB = require("../db");

const db = new DB();

// 简单使用增加方法
async insert(req, res) {
    const body = req.body
    const result = await db.insert('user', [body]);
    res.send({
        code: 200,
        msg: '成功',
        data: result
    })
}

简单方法,仅供参考。

完结撒花🎉🎉🎉

作者: 文章链接: https://reinness.com/posts/89 版权声明:  本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自小陈同学