第六课:数据库集成:MongoDB与Mongoose技术应用

news/2025/3/13 3:27:08/
htmledit_views">

本文详细介绍了如何在Node.js应用程序中集成MongoDBhtml" title=数据库>数据库,并使用Mongoose库进行数据操作。我们将涵盖MongoDB在Ubuntu 20系统中的安装、Bash命令的CRUD操作、Mongoose数据建模(Schema/Model)、关联查询与聚合管道,以及实战案例——用户注册系统的开发。通过本文,你将掌握Node.js与MongoDB集成的完整流程。

1. MongoDB在Ubuntu 20系统中安装与Bash命令的CRUD操作

1.1 MongoDB安装

在Ubuntu 20系统中安装MongoDB,你可以通过以下步骤进行:

方法一:直接安装

导入公共GPG密钥

wget -qO - https://www.html" title=mongodb>mongodb.org/static/pgp/server-7.0.asc | sudo apt-key add -

创建MongoDB源列表文件

echo "deb [ arch=amd64,arm64 ] https://repo.html" title=mongodb>mongodb.org/apt/ubuntu focal/html" title=mongodb>mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/html" title=mongodb>mongodb-org-7.0.list

更新软件包列表并安装MongoDB

sudo apt-get updatesudo apt-get install -y html" title=mongodb>mongodb-org

启动MongoDB服务

sudo systemctl start mongodsudo systemctl enable mongod

方法二:使用Docker镜像

如果你更喜欢使用Docker来管理MongoDB,可以使用以下命令:

docker pull mongodocker run -itd --name mongo_latest -p 27017:27017 mongo

然后,你可以通过docker exec -it mongo_latest mongosh进入MongoDB shell

1.2 Bash命令的CRUD操作

增操作

mongouse myDatabasedb.users.insert({name: "deming_su", age: 22, email: "deming_su@163.com"})

查操作

db.users.find()

更操作

db.users.updateOne({name: "deming_su"}, {$set: {age: 23}})

删操作

db.users.deleteOne({name: "deming_su"})

2. Mongoose数据建模(Schema/Model)

2.1 Mongoose安装

首先,确保你的Node.js环境已经安装完毕,然后通过npm安装Mongoose:

npm install mongoose

2.2 定义Schema

Schema是Mongoose中用于定义文档结构的蓝图。以下是一个简单的用户Schema示例:

javascript">const mongoose = require('mongoose');const userSchema = new mongoose.Schema({id: String,name: String,age: Number,email: {type: String,unique: true}
});
2.3 创建Model

Model是Schema的编译版本,用于创建和操作html" title=数据库>数据库中的文档。你可以使用mongoose.model方法创建Model:

javascript">const User = mongoose.model('User', userSchema);
2.4 CRUD操作

使用Mongoose进行CRUD操作非常简单。以下是一些示例:

增操作

javascript">const mongoose = require('mongoose');
const User = require('./models/user');mongoose.connect('html" title=mongodb>mongodb://localhost:27017/myDatabase', {useNewUrlParser: true,useUnifiedTopology: true
});const newUser = new User({id: "deming_su", name: "deming_su", age: 28, email: "deming_su@163.com"});newUser.save();

查操作

javascript">User.find({id: "deming_su"}, (err, users) => {if (err) {console.error(err);} else {console.log(users);}
});

更操作

javascript">User.findByIdAndUpdate('deming_su', {$set: {age: 29}}, (err, user) => {if (err) {console.error(err);} else {console.log(user);}
});

删操作

javascript">User.findByIdAndDelete('deming_su', (err, user) => {if (err) {console.error(err);} else {console.log(user);}
});

3. 关联查询与聚合管道

3.1 关联查询

在MongoDB中,关联查询通常通过$lookup操作符在聚合管道中实现。假设我们有两个集合:users和orders,每个订单都属于一个用户,我们可以通过user_id字段进行关联查询。

javascript">User.aggregate([{$lookup: {from: 'orders',localField: '_id',foreignField: 'user_id',as: 'orders'}}
]).exec((err, users) => {if (err) {console.error(err);} else {console.log(users);}
});
3.2 聚合管道

聚合管道允许你对集合中的文档进行一系列复杂的转换和聚合操作。以下是一个简单的聚合管道示例,用于统计每个用户的订单总数:

javascript">Order.aggregate([{$group: {_id: '$user_id',totalOrders: { $sum: 1 }}}
]).exec((err, results) => {if (err) {console.error(err);} else {console.log(results);}
});

4. 实战:用户注册系统开发

4.1 系统设计

用户注册系统需要实现以下功能:

  • 用户注册:收集用户信息(如用户名、密码、邮箱等)并保存到html" title=数据库>数据库。
  • 用户登录:验证用户信息并登录系统。
  • 用户注销:清除用户会话并注销系统。
4.2 数据建模

首先,我们需要定义用户数据模型。使用Mongoose,我们可以创建一个简单的用户Schema:

javascript">const mongoose = require('mongoose');const userSchema = new mongoose.Schema({username: {type: String,required: true,unique: true},password: {type: String,required: true},email: {type: String,required: true,unique: true}
});
4.3 实现注册功能

前端(HTML + JavaScript)

html"><!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>User Registration</title>
</head>
<body><form id="registerForm"><label for="username">Username:</label><input type="text" id="username" name="username" required><br><br><label for="password">Password:</label><input type="password" id="password" name="password" required><br><br><label for="email">Email:</label><input type="email" id="email" name="email" required><br><br><button type="submit">Register</button></form><script>document.getElementById('registerForm').addEventListener('submit', async function(event) {event.preventDefault();const username = document.getElementById('username').value;const password = document.getElementById('password').value;const email = document.getElementById('email').value;const response = await fetch('/register', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify({ username, password, email })});const result = await response.json();if (result.success) {alert('Registration successful!');} else {alert('Registration failed: ' + result.message);}});</script>
</body>
</html>

后端(Node.js + Express + Mongoose)

javascript">const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');const app = express();
const port = 3000;mongoose.connect('html" title=mongodb>mongodb://localhost:27017/userRegistration', {useNewUrlParser: true,useUnifiedTopology: true
});app.use(bodyParser.json());const User = require('./models/user');app.post('/register', async (req, res) => {const { username, password, email } = req.body;try {const user = new User({ username, password, email });await user.save();res.json({ success: true });} catch (err) {res.json({ success: false, message: err.message });}
});app.listen(port, () => {console.log(`Server is running on http://localhost:${port}`);
});
4.4 实现登录和注销功能

登录和注销功能的实现与注册类似,这里不再赘述。你可以参考上述代码,通过发送POST请求到/login和/logout端点来实现用户登录和注销功能。

结语

通过本文,你了解了如何在Node.js应用程序中集成MongoDBhtml" title=数据库>数据库,并使用Mongoose库进行数据操作。我们涵盖了MongoDB的安装、Bash命令的CRUD操作、Mongoose数据建模、关联查询与聚合管道,以及实战案例——用户注册系统的开发。希望这些内容对你有所帮助,让你能够更好地掌握Node.js与MongoDB的集成技术。

关注我!!🫵 持续为你带来Nodejs相关内容。


http://www.ppmy.cn/news/1578684.html

相关文章

基于YOLO11深度学习的遥感视角地面房屋建筑检测分割与分析系统【python源码+Pyqt5界面+数据集+训练代码】深度学习实战、目标分割、人工智能

《------往期经典推荐------》 一、AI应用软件开发实战专栏【链接】 项目名称项目名称1.【人脸识别与管理系统开发】2.【车牌识别与自动收费管理系统开发】3.【手势识别系统开发】4.【人脸面部活体检测系统开发】5.【图片风格快速迁移软件开发】6.【人脸表表情识别系统】7.【…

JVM RuntimeDataArea 成分

根据 JVM 规范&#xff0c;运行时数据区&#xff08;Runtime Data Area&#xff09; 是 JVM 内存管理的核心模块&#xff0c;分为以下 5 个主要部分&#xff08;按线程共享性分类&#xff09;&#xff1a; 一、线程私有区域 1. 程序计数器&#xff08;Program Counter Registe…

智能体开发:推理-行动(ReAct)思维链提示

人类在处理一个需要多个步骤才能完成任务时&#xff0c;显著特点是能够将言语推理&#xff08;内心独白&#xff09;和实际行动融合在一起&#xff0c;在面对陌生或不确定的情况时通过这种方法学习新知识&#xff0c;做出决策&#xff0c;并执行&#xff0c;从而应对复杂的任务…

【实战ES】实战 Elasticsearch:快速上手与深度实践-6.1.1RBAC角色权限设计

&#x1f449; 点击关注不迷路 &#x1f449; 点击关注不迷路 &#x1f449; 点击关注不迷路 文章大纲 6.1.1 RBAC角色权限设计深度实践指南1. RBAC核心模型解析1.1 四层权限控制体系1.2 权限继承矩阵 2. 角色定义与权限配置2.1 角色模板设计2.2 权限粒度控制表 3. 企业级权限方…

Python中很常用的100个函数整理

Python 内置函数提供了强大的工具&#xff0c;涵盖数据处理、数学运算、迭代控制、类型转换等。本文总结了 100 个常用内置函数&#xff0c;并配备示例代码&#xff0c;提高编程效率。 1. abs() 取绝对值 print(abs(-10)) # 10 2. all() 判断所有元素是否为真 print(all([…

部署自己的Docker镜像加速仓库

docker-proxy 镜像加速仓库 https://github.com/kubesre/docker-registry-mirrors 自建多平台容器镜像代理服务,支持 Docker Hub, GitHub, Google, k8s, Quay, Microsoft 等镜像仓库. 准备工作 ⚠️ 重要&#xff1a;一台国外的服务器腾讯云特惠服务器推荐&#xff0c;并且未…

Unity辅助工具_头部与svn

Unity调用者按钮增加PlaySideButton using QQu; using UnityEditor; using UnityEngine; [InitializeOnLoad] public class PlaySideButton {static PlaySideButton(){UnityEditorToolbar.RightToolbarGUI.Add(OnRightToolbarGUI);UnityEditorToolbar.LeftToolbarGUI.Add(OnLe…

从零开始 | C语言基础刷题DAY1

❤个人主页&#xff1a;折枝寄北的博客 DAY1[2025.3.11] 1. 求两个数的较大值2.从键盘输入的两个数的大小关系3.一个整数的奇偶性&#xff0c;请判断4. 考试分数是否通过5.考试成绩是否完美&#xff0c;请判断 1. 求两个数的较大值 题目&#xff1a; 写一个函数求两个整数的较…