使用 Nodejs 和 MongoDB 本机驱动程序构建快速灵活的 CRUD API
来源:dev.to
时间:2024-08-06 22:33:52 192浏览 收藏
“纵有疾风来,人生不言弃”,这句话送给正在学习文章的朋友们,也希望在阅读本文《使用 Nodejs 和 MongoDB 本机驱动程序构建快速灵活的 CRUD API》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新文章相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!
将 node.js 和 express 与 mongodb 本机驱动程序结合使用:原因和方式
如果您使用 node.js 和 express,您可能遇到过 mongoose,这是一个流行的 mongodb odm(对象数据建模)库。虽然 mongoose 提供了许多有用的功能,但您可能有理由选择直接使用 mongodb 的本机驱动程序。在这篇文章中,我将带您了解使用 mongodb 本机驱动程序的好处,并分享如何使用它们实现简单的 crud api。
为什么使用 mongodb 本机驱动程序?
性能:mongodb 原生驱动程序通过直接与 mongodb 交互来提供更好的性能,而无需 mongoose 引入的额外抽象层。这对于高性能应用程序特别有益。
灵活性:本机驱动程序可以更好地控制您的查询和数据交互。 mongoose 及其模式和模型强加了一些结构,这可能并不适合每个用例。
减少开销:通过使用本机驱动程序,您可以避免维护 mongoose 模式和模型的额外开销,这可以简化您的代码库。
学习机会:直接使用原生驱动可以帮助你更好地理解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 上的完整代码,并为您自己的项目探索更多功能或增强功能!
还有任何问题欢迎评论。
快乐编码! ?
好了,本文到此结束,带大家了解了《使用 Nodejs 和 MongoDB 本机驱动程序构建快速灵活的 CRUD API》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多文章知识!
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
335 收藏
-
132 收藏
-
483 收藏
-
355 收藏
-
417 收藏
-
224 收藏
-
271 收藏
-
225 收藏
-
253 收藏
-
148 收藏
-
321 收藏
-
391 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习