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

推荐订阅源

S
Security Affairs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Jina AI
Jina AI
P
Palo Alto Networks Blog
GbyAI
GbyAI
大猫的无限游戏
大猫的无限游戏
A
Arctic Wolf
Hugging Face - Blog
Hugging Face - Blog
小众软件
小众软件
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
Blog — PlanetScale
Blog — PlanetScale
S
Schneier on Security
V
Vulnerabilities – Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
雷峰网
雷峰网
T
Tenable Blog
人人都是产品经理
人人都是产品经理
T
Tor Project blog
C
Cyber Attacks, Cyber Crime and Cyber Security
AWS News Blog
AWS News Blog
Microsoft Security Blog
Microsoft Security Blog
J
Java Code Geeks
Scott Helme
Scott Helme
SecWiki News
SecWiki News
C
CERT Recently Published Vulnerability Notes
Recorded Future
Recorded Future
I
InfoQ
Security Archives - TechRepublic
Security Archives - TechRepublic
Help Net Security
Help Net Security
Cloudbric
Cloudbric
C
Check Point Blog
Engineering at Meta
Engineering at Meta
TaoSecurity Blog
TaoSecurity Blog
B
Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园_首页
N
News and Events Feed by Topic
云风的 BLOG
云风的 BLOG
MyScale Blog
MyScale Blog
腾讯CDC
量子位
Application and Cybersecurity Blog
Application and Cybersecurity Blog
K
Kaspersky official blog
Vercel News
Vercel News
F
Full Disclosure
T
Troy Hunt's Blog
Forbes - Security
Forbes - Security
S
Security @ Cisco Blogs

小陈同学 - 后端

从 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 许可协议。转载请注明来自小陈同学