首頁  >  文章  >  web前端  >  使用 Node.js 和 MongoDB 本機驅動程式建立快速且靈活的 CRUD API

使用 Node.js 和 MongoDB 本機驅動程式建立快速且靈活的 CRUD API

WBOY
WBOY原創
2024-08-07 01:21:13709瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn