-
MongoDB数据库
-
安装mongoDB数据库文件和可视化程序
-
安装和引入mongoDB包
安装包: npm i mongoose -S 引入mongodb: const mongoose = require("mongoose"); 链接数据库服务: mongoose .connect("mongodb://localhost:27017/goudan",{ useNewUrlParser: true,useUnifiedTopology:true }) //connect返回一个promise,所以后面可以直接通过then catch来检测是否连接成功 .then(()=>{console.log("数据库连接成功.");}) .catch(()=>{console.log("数据库连接失败!");});
-
案列:简单的登录注册 写入数据库
入口文件:index.js const express = require("express"); const path = require("path"); let app = express(); app.listen(8899); app.use(express.json()); app.use(express.urlencoded({extended:true})); app.use(express.static(path.join(__dirname,"./static"))); app.post("/register",require("./router/register"));
后端数据库接口文件: ./db/user.js /*引入mongoose包*/ const mongoose = require("mongoose"); mongoose .connect("mongodb://localhost:27017/goudan",{ useNewUrlParser: true,useUnifiedTopology:true } ) /*connect返回一个promise,所以后面可以直接通过then catch来检测是否连接成功*/ .then(()=>{console.log("数据库连接成功.");}) .catch(()=>{console.log("数据库连接失败!");}); /*数据库中建立一个用户表 建表之前得先定义好表的规则 */ //得到Schema以用来创建规则 let Schema = mongoose.Schema; //user表的规则 let userSchema = new Schema( { /*key 以及规则*/ username : {type: String, required: true}, //用户名 required表示是否必须的 password: {type: String, required: true}, /*密码*/ age : Number, /*年龄*/ sex : String, /*性别*/ status : {type: String, required: false, default:"这个人很拽,没有个性签名。"}/*个性签名*/ }, {versionKey:false} //取消数据库的_v这个版本属性 ); //规则创建好了后,接着就是建表 //参数一:表名 //参数二:Schema规则 let user = mongoose.model("user",userSchema); //创建user表 并使用以上的创建的userSchema规则 //通过建表之后返回的表对象进行各种数据的增删改查操作 /*增加数据的操作肯定不是和建表放在一个文件夹里面的 只有用户和页面进行了交互之后,通过ajax发送了注册的信息,然后再往数据库增加数据的 */ module.exports = user; //将user返回在另外的文件中去进行表的创建
后端写入数据库接口: ./router/rehister.js const user = require("../db/user"); module.exports = (req,res)=>{ let data = req.body; /*增加数据*/ user.create({ username : data.username, password : data.password, age : data.age*1, sex : data.sex*1?"男":"女", status : data.status || undefined }) .then(()=>{ console.log("后端成功"); res.send("恭喜注册成功"); //返回给前端的成功数据,可以是个页面 }) .catch((e)=>{ console.log("后端失败",e); res.send("注册失败"); //返回给前端的失败数据 }); };
前端html注册页面: ./static/index.html <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> //form表单请求数据: <form action="/register" method="post"> 用户名:<input type="text" name="username"><br> 密--码:<input type="password" name="password"><br> 年--龄:<input type="text" name="age"><br> 性--别:<input type="radio" name="sex" value="1">男 <input type="radio" name="sex" value="0">女 <br> 个性签名:<br><textarea name="status" id="" cols="30" rows="10"></textarea> <br><br><input type="submit"> </form> </body> </html>
MongoDB数据库
最新推荐文章于 2024-09-14 19:55:29 发布