”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 Node.js 和 MongoDB 本机驱动程序构建快速灵活的 CRUD API

使用 Node.js 和 MongoDB 本机驱动程序构建快速灵活的 CRUD API

发布于2024-08-21
浏览:123

Building a Fast and Flexible CRUD API with Node.js and MongoDB Native Drivers

将 Node.js 和 Express 与 MongoDB 本机驱动程序结合使用:原因和方式

如果您使用 Node.js 和 Express,您可能遇到过 Mongoose,这是一个流行的 MongoDB ODM(对象数据建模)库。虽然 Mongoose 提供了许多有用的功能,但您可能有理由选择直接使用 MongoDB 的本机驱动程序。在这篇文章中,我将向您介绍使用 MongoDB 本机驱动程序的好处,并分享如何使用它们实现简单的 CRUD API。

为什么使用 MongoDB 本机驱动程序?

  1. 性能:MongoDB 原生驱动程序通过直接与 MongoDB 交互来提供更好的性能,而无需 Mongoose 引入的额外抽象层。这对于高性能应用程序特别有益。

  2. 灵活性:本机驱动程序可以更好地控制您的查询和数据交互。 Mongoose 及其模式和模型强加了一些结构,这可能并不适合每个用例。

  3. 减少开销:通过使用本机驱动程序,您可以避免维护 Mongoose 架构和模型的额外开销,这可以简化您的代码库。

  4. 学习机会:直接使用原生驱动程序可以帮助您更好地了解 MongoDB 的操作,并且可以是一次很棒的学习体验。

使用 MongoDB 本机驱动程序实现 CRUD API

以下是有关如何使用 Node.js、Express 和 MongoDB 本机驱动程序设置简单 CRUD API 的分步指南。

1. 设置数据库连接

创建utils/db.js文件来管理MongoDB连接:

require('dotenv').config()
const dbConfig = require('../config/db.config');
const { MongoClient } = require('mongodb');

const client = new MongoClient(dbConfig.url);

let _db;
let connectPromise;

async function connectToDb() {
    if (!connectPromise) {
        connectPromise = new Promise(async (resolve, reject) => {
            try {
                await client.connect();
                console.log('Connected to the database ?', client.s.options.dbName);
                _db = client.db();
                resolve(_db);
            } catch (error) {
                console.error('Error connecting to the database:', error);
                reject(error);
            }
        });
    }
    return connectPromise;
}

function getDb() {
    if (!_db) {
        throw new Error('Database not connected');
    }
    return _db;
}

function isDbConnected() {
    return Boolean(_db);
}

module.exports = { connectToDb, getDb, isDbConnected };

2. 定义你的模型

创建 models/model.js 文件以与 MongoDB 集合交互:

const { ObjectId } = require('mongodb');
const db = require('../utils/db');

class AppModel {
    constructor($collection) {
        this.collection = null;

        (async () => {
            if (!db.isDbConnected()) {
                console.log('Waiting for the database to connect...');
                await db.connectToDb();
            }
            this.collection = db.getDb().collection($collection);
            console.log('Collection name:', $collection);
        })();
    }

    async find() {
        return await this.collection.find().toArray();
    }

    async findOne(condition = {}) {
        const result = await this.collection.findOne(condition);
        return result || 'No document Found!';
    }

    async create(data) {
        data.createdAt = new Date();
        data.updatedAt = new Date();
        let result = await this.collection.insertOne(data);
        return `${result.insertedId} Inserted successfully`;
    }

    async update(id, data) {
        let condition = await this.collection.findOne({ _id: new ObjectId(id) });
        if (condition) {
            const result = await this.collection.updateOne({ _id: new ObjectId(id) }, { $set: { ...data, updatedAt: new Date() } });
            return `${result.modifiedCount > 0} Updated successfully!`;
        } else {
            return `No document found with ${id}`;
        }
    }

    async deleteOne(id) {
        const condition = await this.collection.findOne({ _id: new ObjectId(id) });
        if (condition) {
            const result = await this.collection.deleteOne({ _id: new ObjectId(id) });
            return `${result.deletedCount > 0} Deleted successfully!`;
        } else {
            return `No document found with ${id}`;
        }
    }
}

module.exports = AppModel;

3. 设置路线

创建一个index.js文件来定义您的API路由:

const express = require('express');
const router = express.Router();

const users = require('../controllers/userController');

router.get("/users", users.findAll);
router.post("/users", users.create);
router.put("/users", users.update);
router.get("/users/:id", users.findOne);
router.delete("/users/:id", users.deleteOne);

module.exports = router;

4. 实施控制器

创建一个 userController.js 文件来处理您的 CRUD 操作:

const { ObjectId } = require('mongodb');
const Model = require('../models/model');

const model = new Model('users');

let userController = {
    async findAll(req, res) {
        model.find()
            .then(data => res.send(data))
            .catch(err => res.status(500).send({ message: err.message }));
    },
    async findOne(req, res) {
        let condition = { _id: new ObjectId(req.params.id) };
        model.findOne(condition)
            .then(data => res.send(data))
            .catch(err => res.status(500).send({ message: err.message }));
    },
    create(req, res) {
        let data = req.body;
        model.create(data)
            .then(data => res.send(data))
            .catch(error => res.status(500).send({ message: error.message }));
    },
    update(req, res) {
        let id = req.body._id;
        let data = req.body;
        model.update(id, data)
            .then(data => res.send(data))
            .catch(error => res.status(500).send({ message: error.message }));
    },
    deleteOne(req, res) {
        let id = new ObjectId(req.params.id);
        model.deleteOne(id)
            .then(data => res.send(data))
            .catch(error => res.status(500).send({ message: error.message }));
    }
}

module.exports = userController;

5. 配置

将 MongoDB 连接字符串存储在 .env 文件中并创建 db.config.js 文件来加载它:

module.exports = {
    url: process.env.DB_CONFIG,
};

结论

从 Mongoose 切换到 MongoDB 本机驱动程序可能是某些项目的战略选择,可提供性能优势和更大的灵活性。此处提供的实现应该为您开始使用 Node.js 和 MongoDB 本机驱动程序构建应用程序奠定坚实的基础。

请随意查看 GitHub 上的完整代码,并为您自己的项目探索更多功能或增强功能!

还有什么问题欢迎评论。

编码愉快! ?

版本声明 本文转载于:https://dev.to/jafeer_shaik_f5895990c4ae/building-a-fast-and-flexible-crud-api-with-nodejs-and-mongodb-native-drivers-2i1h?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何使用Java.net.urlConnection和Multipart/form-data编码使用其他参数上传文件?
    如何使用Java.net.urlConnection和Multipart/form-data编码使用其他参数上传文件?
    使用http request 上传文件上传到http server,同时也提交其他参数,java.net.net.urlconnection and Multipart/form-data Encoding是普遍的。 Here's a breakdown of the process:Mu...
    编程 发布于2025-03-09
  • 为什么使用Firefox后退按钮时JavaScript执行停止?
    为什么使用Firefox后退按钮时JavaScript执行停止?
    导航历史记录问题:JavaScript使用Firefox Back Back 此行为是由浏览器缓存JavaScript资源引起的。要解决此问题并确保在后续页面访问中执行脚本,Firefox用户应设置一个空功能。 警报'); }; alert('inline Alert')...
    编程 发布于2025-03-09
  • 如何使用FormData()处理多个文件上传?
    如何使用FormData()处理多个文件上传?
    )处理多个文件输入时,通常需要处理多个文件上传时,通常是必要的。 The fd.append("fileToUpload[]", files[x]); method can be used for this purpose, allowing you to send multi...
    编程 发布于2025-03-09
  • 如何使用组在MySQL中旋转数据?
    如何使用组在MySQL中旋转数据?
    在关系数据库中使用mySQL组使用mySQL组进行查询结果,在关系数据库中使用MySQL组,转移数据的数据是指重新排列的行和列的重排以增强数据可视化。在这里,我们面对一个共同的挑战:使用组的组将数据从基于行的基于列的转换为基于列。 Let's consider the following ...
    编程 发布于2025-03-09
  • 为什么Microsoft Visual C ++无法正确实现两台模板的实例?
    为什么Microsoft Visual C ++无法正确实现两台模板的实例?
    The Mystery of "Broken" Two-Phase Template Instantiation in Microsoft Visual C Problem Statement:Users commonly express concerns that Micro...
    编程 发布于2025-03-09
  • 大批
    大批
    [2 数组是对象,因此它们在JS中也具有方法。 切片(开始):在新数组中提取部分数组,而无需突变原始数组。 令ARR = ['a','b','c','d','e']; // USECASE:提取直到索引作...
    编程 发布于2025-03-09
  • 为什么不使用CSS`content'属性显示图像?
    为什么不使用CSS`content'属性显示图像?
    在Firefox extemers属性为某些图像很大,&& && && &&华倍华倍[华氏华倍华氏度]很少见,却是某些浏览属性很少,尤其是特定于Firefox的某些浏览器未能在使用内容属性引用时未能显示图像的情况。这可以在提供的CSS类中看到:。googlepic { 内容:url(&#...
    编程 发布于2025-03-09
  • HTML格式标签
    HTML格式标签
    HTML 格式化元素 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without us...
    编程 发布于2025-03-09
  • 可以在纯CS中将多个粘性元素彼此堆叠在一起吗?
    可以在纯CS中将多个粘性元素彼此堆叠在一起吗?
    [2这里: https://webthemez.com/demo/sticky-multi-header-scroll/index.html </main> <section> { display:grid; grid-template-...
    编程 发布于2025-03-09
  • 对象拟合:IE和Edge中的封面失败,如何修复?
    对象拟合:IE和Edge中的封面失败,如何修复?
    解决此问题,我们采用了一个巧妙的CSS解决方案来解决问题:左:50%; 高度:auto; 宽度:100%; //对于水平块 ,使用绝对定位将图像定位在中心,以object-fit:object-fit:cover in IE和edge消除了问题。现在,图像将按比例扩展,保持所需的效果而不会失真。...
    编程 发布于2025-03-09
  • 我可以将加密从McRypt迁移到OpenSSL,并使用OpenSSL迁移MCRYPT加密数据?
    我可以将加密从McRypt迁移到OpenSSL,并使用OpenSSL迁移MCRYPT加密数据?
    将我的加密库从mcrypt升级到openssl 问题:是否可以将我的加密库从McRypt升级到OpenSSL?如果是这样,如何?答案:是的,可以将您的Encryption库从McRypt升级到OpenSSL。可以使用openssl。附加说明: [openssl_decrypt()函数要求iv参...
    编程 发布于2025-03-09
  • 如何检查对象是否具有Python中的特定属性?
    如何检查对象是否具有Python中的特定属性?
    方法来确定对象属性存在寻求一种方法来验证对象中特定属性的存在。考虑以下示例,其中尝试访问不确定属性会引起错误: >>> a = someClass() >>> A.property Trackback(最近的最新电话): 文件“ ”,第1行, AttributeError: SomeClass...
    编程 发布于2025-03-09
  • 如何在JavaScript对象中动态设置键?
    如何在JavaScript对象中动态设置键?
    在尝试为JavaScript对象创建动态键时,如何使用此Syntax jsObj['key' i] = 'example' 1;不工作。正确的方法采用方括号: jsobj ['key''i] ='example'1; 在JavaScript中,数组是一...
    编程 发布于2025-03-09
  • 如何克服PHP的功能重新定义限制?
    如何克服PHP的功能重新定义限制?
    克服PHP的函数重新定义限制在PHP中,多次定义一个相同名称的函数是一个no-no。尝试这样做,如提供的代码段所示,将导致可怕的“不能重新列出”错误。 但是,PHP工具腰带中有一个隐藏的宝石:runkit扩展。它使您能够灵活地重新定义函数。 runkit_function_renction_re...
    编程 发布于2025-03-09
  • Java是否允许多种返回类型:仔细研究通用方法?
    Java是否允许多种返回类型:仔细研究通用方法?
    在Java中的多个返回类型:一种误解类型:在Java编程中揭示,在Java编程中,Peculiar方法签名可能会出现,可能会出现,使开发人员陷入困境,使开发人员陷入困境。 getResult(string s); ,其中foo是自定义类。该方法声明似乎拥有两种返回类型:列表和E。但这确实是如此吗...
    编程 发布于2025-03-09

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3