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

MongoDB 네이티브 드라이버와 함께 Node.js 및 Express를 사용하는 이유 및 방법

Node.js 및 Express로 작업하는 경우 MongoDB용 인기 ODM(객체 데이터 모델링) 라이브러리인 Mongoose를 접했을 것입니다. Mongoose는 많은 유용한 기능을 제공하지만 MongoDB의 기본 드라이버로 직접 작업하기로 선택한 이유가 있습니다. 이 게시물에서는 MongoDB 네이티브 드라이버 사용의 이점을 안내하고 이를 사용하여 간단한 CRUD API를 구현하는 방법을 공유하겠습니다.

MongoDB 네이티브 드라이버를 사용하는 이유는 무엇입니까?

  1. 성능: MongoDB 네이티브 드라이버는 Mongoose가 도입하는 추가 추상화 계층 없이 MongoDB와 직접 상호 작용하여 더 나은 성능을 제공합니다. 이는 고성능 애플리케이션에 특히 유용할 수 있습니다.

  2. 유연성: 기본 드라이버는 쿼리 및 데이터 상호 작용을 더 효과적으로 제어할 수 있습니다. 스키마와 모델을 갖춘 Mongoose는 일부 사용 사례에 이상적이지 않을 수 있는 일부 구조를 부과합니다.

  3. 오버헤드 감소: 기본 드라이버를 사용하면 Mongoose 스키마 및 모델을 유지 관리하는 데 따른 추가 오버헤드를 방지하여 코드베이스를 단순화할 수 있습니다.

  4. 학습 기회: 기본 드라이버로 직접 작업하면 MongoDB의 운영을 더 잘 이해하는 데 도움이 되며 훌륭한 학습 경험이 될 수 있습니다.

MongoDB 네이티브 드라이버로 CRUD API 구현

다음은 Node.js, Express 및 MongoDB 네이티브 드라이버를 사용하여 간단한 CRUD API를 설정하는 방법에 대한 단계별 가이드입니다.

1. 데이터베이스 연결 설정

MongoDB 연결을 관리하기 위해 utils/db.js 파일을 만듭니다.

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. 모델 정의

MongoDB 컬렉션과 상호 작용할 models/model.js 파일을 만듭니다.

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. 컨트롤러 구현

CRUD 작업을 처리할 userController.js 파일을 만듭니다.

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 학습자의 빠른 성장을 도와주세요!