Express的使用笔记7 将数据保存到数据库中
前面我们在使用的时候是将数据保存在json中,显然是不够方便的,也不够专业,这里我们尝试将数据保存到数据库中。
1. 跟随这个项目的demo,使用的是MongoDB,那首先得安装一个MongoDB咯。
1) 先下载一个zip安装包,我选择的是5版本的 https://www.mongodb.com/try/download/community
可能会失败很多次,可以刷新或者停留一会,反正就是别放弃就行~
2)安装一下,流程可以参考这个教程 https://juejin.cn/post/6844903912000978952
运行: 关掉的话这个窗口就没有了~
2.下载一个Navicat来,创建一个collection,选择MongoDB,然后就把默认的地址和端口配置一下
如图:
点击测试,如果连接成功会显示如下图:
3.回到Express项目中
1) 安装一下依赖:npm install mongoose
2)在model文件目录下创建一个index.js文件,里面引入并暴露我们的db
const mongoose = require("mongoose");
// 连接MongoDB数据库
mongoose.connect("mongodb://localhost:27017/realworld", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
var db = mongoose.connection;
db.on("error", console.error.bind(console, "数据库连接失败~"));
db.once("open", function () {
console.log("数据库连接成功!");
});
module.exports=db; //其实不暴露也行,因为在app.js中我们也只是引入而已,不需要使用到db
3)在app.js中引入一下 require('./model')
4)运行项目看一下控制台~~ 这就成功了~
5)开始尝试往数据库里面写入数据吧~
4.起飞使用 (这里必须单开一个title才行)
1)为了模块化管理,咱们前端这边就在model中按主题创建各js文件,如:用户模块
创建 model/user.js,在里面放置用户相关api参数的字段
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
bio: {
type: String,
defualt: null,
},
image: {
type: String,
defualt: null,
},
createDate: {
type: Date,
default: Date.now,
},
updateDate: {
type: Date,
default: Date.now,
},
});
module.exports = userSchema;
2)在index.js中组织导出模型类
module.exports={
User:mongoose.model('User',require('./user'))
}
3)在conctroller/user.js中,引入刚刚导出的User,然后进行使用
const {User} =require("../model");
// 用户注册
exports.register = async (req, res,next) => {
try {
console.log(req.body,'请求体')
// 数据验证:1.1基础数据验证,1.2业务数据验证
// 验证通过,将数据保存到数据库中 mongooseDB
const user = new User(req.body.user)
await user.save()
// 发送成功
res.status(200).json({user})
} catch (err) {
next(err);
}
};
4)在postman中测试一下
5)去数据库里看看是否写入成功了~~
鉴于我们可能会有不同的环境配置不同的数据库地址,那我们就可以在config文件夹中处理咯
module.exports={
dburl:"mongodb://localhost:27017/realworld"
}
然后又回去引入这个地址对应的变量咯
const mongoose = require("mongoose");
const {dburl} = require('../config/config.default')
// 连接MongoDB数据库
mongoose.connect(dburl, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
var db = mongoose.connection;
db.on("error", console.error.bind(console, "数据库连接失败~"));
db.once("open", function () {
console.log("数据库连接成功!");
});
module.exports={
User:mongoose.model('User',require('./user'))
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律