当前位置: 首页 > news >正文

使用Nodejs + express连接数据库mongoose

在这里插入图片描述

文章目录

  • 先创建一个js文档
  • 安装 MongoDB 驱动程序:
  • 引入 MongoDB 模块:
  • 设置数据库连接:
  • 新建一个表试试
  • 执行数据库操作:
  • 关闭数据库连接:


前面需要准备的内容可看前面的文章:
Express框架搭建项目 node.js
简单用Nodejs + express 编写接口

连接 mongoose数据库需要使用 Node.js 的 mongoose驱动程序。在 Express 应用程序中使用 mongoose驱动程序时,需要执行以下步骤

先创建一个js文档

db.js文档
在这里插入图片描述

安装 MongoDB 驱动程序:

在你的项目目录下使用 npm 或 yarn 安装 mongoose驱动程序。

npm install mongoose

在这里插入图片描述

引入 MongoDB 模块:

在 Express 应用程序的文件中引入 MongoDB 模块。

const mongodb = require('mongoose');

在这里插入图片描述

设置数据库连接:

创建一个 mongoose客户端,并通过客户端连接到 mongoose数据库。

const mongoose = require('mongoose');// mongoose连接字符串,包括数据库地址和名称
mongoose.connect('mongodb://localhost:27017/mydatabase').then(() => {console.log('Connected to the database');}).catch((err) => {console.error('Failed to connect to the database:', err);});

在这里插入图片描述

在上面的代码中,uri 变量包含了 mongoose数据库的连接字符串,其中包括数据库地址和名称。然后,创建一个新的 mongoose 实例,并通过 connect() 方法连接到数据库。在连接成功后,可以执行数据库操作,例如查询、插入、更新或删除文档。

新建一个表试试

const userValue =new mongoose.Schema({name: String,age: Number,email: String,password: String,phone: String,address: String,gender: String,dob: Date,createdAt: { type: Date, default: Date.now },updatedAt: { type: Date, default: Date.now }
});const User = mongoose.model('User', userValue);

在上面的代码中,先声明一个表的格式。使用new mongooseSchema函数,内容为需要保存的字段。
在这里插入图片描述
再使用module.exports将表传出去:

const mongoose = require('mongoose');// MongoDB 连接字符串,包括数据库地址和名称
mongoose.connect('mongodb://localhost:27017/mydatabase').then(() => {console.log('Connected to the database');}).catch((err) => {console.error('Failed to connect to the database:', err);});const userValue =new mongoose.Schema({name: String,age: Number,email: String,password: String,phone: String,address: String,gender: String,dob: Date,createdAt: { type: Date, default: Date.now },updatedAt: { type: Date, default: Date.now }
});const User = mongoose.model('User', userValue);module.exports = { User };

在这里插入图片描述

再使用index页面接收一下:

const { User }= require('./db');

在这里插入图片描述

执行数据库操作:

在连接成功后,可以在回调函数中执行数据库操作。

// 在连接成功后执行数据库操作
client.connect(err => {if (err) {console.error('Failed to connect to the database:', err);return;}console.log('Connected successfully to the database');const db = client.db();// 查询所有文档db.collection('mycollection').find().toArray((err, docs) => {if (err) {console.error('Error fetching documents:', err);return;}console.log('Documents:', docs);});// 插入文档db.collection('mycollection').insertOne({ name: 'John', age: 30 }, (err, result) => {if (err) {console.error('Error inserting document:', err);return;}console.log('Document inserted:', result.insertedId);});// 更新文档db.collection('mycollection').updateOne({ name: 'John' }, { $set: { age: 35 } }, (err, result) => {if (err) {console.error('Error updating document:', err);return;}console.log('Document updated:', result.modifiedCount);});// 删除文档db.collection('mycollection').deleteOne({ name: 'John' }, (err, result) => {if (err) {console.error('Error deleting document:', err);return;}console.log('Document deleted:', result.deletedCount);});
});

在上面的代码中,db.collection() 方法用于获取集合对象,然后可以使用该集合对象执行查询、插入、更新或删除操作。

关闭数据库连接:

在完成数据库操作后,记得关闭数据库连接,释放资源。

// 关闭数据库连接
client.close();

这样,你的 Express 应用程序就可以连接到 mongoose数据库并执行数据库操作了。记得根据你的实际需求修改连接字符串和数据库操作。

您好,我是肥晨。
欢迎关注我获取前端学习资源,日常分享技术变革,生存法则;行业内幕,洞察先机。

http://www.lryc.cn/news/336909.html

相关文章:

  • 朗致集团面试-Java架构师
  • Ubuntu 23.10 搜狗拼音输入法闪屏解决
  • 备战蓝桥杯---刷杂题2
  • .[[backup@waifu.club]].svh勒索病毒数据怎么处理|数据解密恢复
  • SpringFramework实战指南(八)
  • Ceph学习 -4.Ceph组件介绍
  • Python100个库分享第13个—awesome-slugify(处理Unicode)
  • 01 SQL基础 -- 初识数据库与安装
  • PyTorch搭建Autoformer实现长序列时间序列预测
  • FFmpeg: 简易ijkplayer播放器实现--06封装打开和关闭stream
  • 使用Android完成案例教学
  • 面向对象设计原则实验“依赖倒置原则”
  • PMP考试到底难在哪里?
  • Linux执行命令监控详细实现原理和使用教程,以及相关工具的使用
  • 算法设计与分析实验报告c++实现(生命游戏、带锁的门、三壶谜题、串匹配问题、交替放置的碟子)
  • 【电子通识】热风枪的结构与使用方法
  • mysql知识点
  • css Animation 动画-右进左出
  • 第十三届蓝桥杯省赛大学B组填空题(c++)
  • 天星金融(原小米金融)深耕金融知识领域,助力消费者提升金融素养
  • 中国手机频段介绍
  • 企业如何使用SNP Glue将SAP与Snowflake集成?
  • 算法设计与分析实验报告c++实现(最近点对问题、循环赛日程安排问题、排序问题、棋盘覆盖问题)
  • Vue - 你知道Vue中computed和watch的区别吗
  • POJ2976 Dropping tests——P4377 [USACO18OPEN] Talent Show G 【分数规划二分法+贪心/背包】
  • 【生产实习-毕设】pyspark学生成绩分析与预测(上)
  • 【华为笔试题汇总】2024-04-10-华为春招笔试题(第二套)-三语言题解(CPP/Python/Java)
  • Windows 文件夹被占用无法删除
  • PHP+MySQL组合开发 易企秀H5场景源码系统 带完整的安装代码包以及搭建教程
  • 抖音小店入驻有什么条件?资金少,没经验的普通人做得起吗?