首页 > web前端 > js教程 > 正文

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

WBOY
发布: 2024-08-07 01:21:13
原创
705 人浏览过

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 上的完整代码,并为您自己的项目探索更多功能或增强功能!

还有什么问题欢迎评论。

编码愉快! ?

以上是使用 Node.js 和 MongoDB 本机驱动程序构建快速灵活的 CRUD API的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!