NodeJS MongoDB⑦

文章目录

  • ✨文章有误请指正,如果觉得对你有用,请点三连一波,蟹蟹支持😘
  • 前言
  • Node&MongoDB
  •     第一步 连接数据库
  •     第二步 创建User Mongodb模型
  •     第三步 简单使用 Mongodb命令
  •     第四步 规范使用 Mongodb命令 (RESTful架构)
  • 总结

✨文章有误请指正,如果觉得对你有用,请点三连一波,蟹蟹支持😘

                    ⡖⠒⠒⠒⠤⢄⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸   ⠀⠀⠀⡼⠀⠀⠀⠀ ⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢶⣲⡴⣗⣲⡦⢤⡏⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣰⠋⠉⠉⠓⠛⠿⢷⣶⣦⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠇⠀⠀⠀⠀⠀⠀⠘⡇⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡞⠀⠀⠀⠀⠀⠀⠀⢰⠇⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⡴⠊⠉⠳⡄⠀⢀⣀⣀⡀⠀⣸⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⢸⠃⠀⠰⠆⣿⡞⠉⠀⠀⠉⠲⡏⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠈⢧⡀⣀⡴⠛⡇⠀⠈⠃⠀⠀⡗⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣱⠃⡴⠙⠢⠤⣀⠤⡾⠁⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⢀⡇⣇⡼⠁⠀⠀⠀⠀⢰⠃⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⣸⢠⣉⣀⡴⠙⠀⠀⠀⣼⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⡏⠀⠈⠁⠀⠀⠀⠀⢀⡇⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⢸⠃⠀⠀⠀⠀⠀⠀⠀⡼⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⢸⠀⠀⠀⠀⠀⠀⠀⣰⠃⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⣀⠤⠚⣶⡀⢠⠄⡰⠃⣠⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⢀⣠⠔⣋⣷⣠⡞⠀⠉⠙⠛⠋⢩⡀⠈⠳⣄⠀⠀⠀⠀⠀⠀⠀
⠀⡏⢴⠋⠁⠀⣸⠁⠀⠀⠀⠀⠀ ⠀⣹⢦⣶⡛⠳⣄⠀⠀⠀⠀⠀
⠀⠙⣌⠳⣄⠀⡇   不能   ⡏⠀⠀  ⠈⠳⡌⣦⠀⠀⠀⠀
⠀⠀⠈⢳⣈⣻⡇   白嫖 ⢰⣇⣀⡠⠴⢊⡡⠋⠀⠀⠀⠀
⠀⠀⠀⠀⠳⢿⡇⠀⠀⠀⠀⠀⠀⢸⣻⣶⡶⠊⠁⠀⠀
⠀⠀⠀⠀⠀⢠⠟⠙⠓⠒⠒⠒⠒⢾⡛⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⣠⠏⠀⣸⠏⠉⠉⠳⣄⠀⠙⢆⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⡰⠃⠀⡴⠃⠀⠀⠀⠀⠈⢦⡀⠈⠳⡄⠀⠀⠀⠀⠀⠀⠀
⠀⠀⣸⠳⣤⠎⠀⠀⠀⠀⠀⠀⠀⠀⠙⢄⡤⢯⡀⠀⠀⠀⠀⠀⠀
⠀⠐⡇⠸⡅⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⡆⢳⠀⠀⠀⠀⠀⠀
⠀⠀⠹⡄⠹⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣇⠸⡆⠀⠀⠀⠀⠀
⠀⠀⠀⠹⡄⢳⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⡀⣧⠀⠀⠀⠀⠀
⠀⠀⠀⠀⢹⡤⠳⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣷⠚⣆⠀⠀⠀⠀
⠀⠀⠀⡠⠊⠉⠉⢹⡀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡎⠉⠀⠙⢦⡀⠀
⠀⠀⠾⠤⠤⠶⠒⠊⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠙⠒⠲⠤⠽   

前言

  1. Node.js是一个javascript运行环境。它让javascript可以开发后端程序,实现几乎其他后端语言实现的所有功能,可以与“`PHP、Java、Python、.NET、Ruby等后端语言平起平坐。
  2. Nodejs是基于V8引擎,V8是Google发布的开源JavaScript引擎,本身就是用于Chrome浏览器的JS解释,但是Node之父 Ryan Dahl把这V8搬到了服务器上,用于做服务器的软件。

Node&MongoDB

  • 操作数据库模块 : npm install mongoose
  • Mongoose Npm : https://www.npmjs.com/package/mongoose

    第一步 连接数据库

//文件夹规范 config文件夹 → db.config.js

//连接数据库 通过Require导入模块链接数据库自动链接
const mongoose = require("mongoose")

const serverName = "MyDB"

//插入集合和数据,数据库serverName会自动创建
mongoose.connect(`mongodb://127.0.0.1:27017/${serverName}`).then(() => {
    console.log("数据库连接成功!");
})

    第二步 创建User Mongodb模型

//文件夹规范 modul文件夹 → UserModul.js

const mongoose = require("mongoose") //导入mongoose 以连接上了

//限制模型数据类型
const Schema = mongoose.Schema
const UserType = {
    username:String,
    password:String,
    age:Number
}

// 模型user 将会创建对应 users 集合
const UserModel = mongoose.model("user",new Schema(UserType))

module.exports = UserModel
  1. 返回UserModel方法使用

使用如 ↓

增加数据
UserModel.create({
    username,userpassword
})


查询数据
UserModel.find({username:"kerwin"},
["username","password"])
.sort({createTime:-1}).skip(10).limit(10)


更新数据
UserModel.updateOne({
    _id : ?
},{
    introduction,username,gender,avatar
})

删除数据
UserModel.deleteOne({_id})

    第三步 简单使用 Mongodb命令

客户端

<!DOCTYPE html>
<html>

<head>
  <title>
    Login客户端
  </title>
</head>

<body>
  <h1>mongodb的增删改查的演示</h1>
  <div>
    <div>用户名:<input id="username" /></div>
    <div>密码:<input type="password" id="password" /></div>
    <div>年龄:<input type="number" id="age" /></div>
    <div><button id="register">注册</button></div>
  </div>
  <hr>
  <div>
    <button id="update">更新</button>
    <button id="delete">删除</button>
  </div>
  <hr>

  <table border="1">
    <thead>
      <tr>
        <td>id</td>
        <td>用户名</td>
        <td>年龄</td>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>

  <script>
    var register = document.querySelector("#register")
    var update = document.querySelector("#update")
    var deletebutton = document.querySelector("#delete")
    var username = document.querySelector("#username")
    var password = document.querySelector("#password")
    var age = document.querySelector("#age")

    //注册
    register.onclick = () => {
      fetch("/api/user/add", {
        method: "POST",
        body: JSON.stringify({
          username: username.value,
          password: password.value,
          age: age.value
        }),
        headers: {
          "Content-Type": "application/json"
        }
      }).then(res => res.json()).then(res => {
        console.log(res)
      })
    }

    //更新数据
    update.onclick = () => {
      fetch("/api/user/update/?", {
        method: "POST",
        body: JSON.stringify({
          username: "修改的名字",
          password: "修改的密码",
          age: 1
        }),
        headers: {
          "Content-Type": "application/json"
        }
      }).then(res => res.json()).then(res => {
        console.log(res)
      })
    }

    //删除数据
    deletebutton.onclick = () => {
      fetch("/api/user/delete/?").then(res => res.json()).then(res => {
        console.log(res)
      })
    }

    //渲染列表
    fetch("/api/user/list?page=1&limit=10").then(res => res.json()).then(res => {
      var tbody = document.querySelector("tbody")
      tbody.innerHTML = res.map(item => `
          <tr>
            <td>${item._id}</td>  
            <td>${item.username}</td>  
            <td>${item.age}</td>  
          </tr>
        `).join("")
    })
  </script>
</body>

</html>

服务器

//------用户注册接口 (插入数据)------  
app.post("/user/add",(req,res)=>{
//获取数据
  const {username,password,age} = req.body
  UserModel.create({
    username,password,age
  }).then(data=>{
    console.log(data) //成功获取的数据
    res.send({ //返回客户端数据
      ok:1
    })
  })
})

//------用户修改数据接口 (更新数据)------  
app.post("/user/update/:myid", (req, res) => {
  const { username, password, age } = req.body
  UserModel.updateOne({ _id: req.params.myid }, {
    username, age, password
  }).then(data => {
    res.send({ //返回客户端数据
      ok: 1
    })
  })
})

//------用户删除数据接口 (删除数据)------  
app.get("/user/delete/:myid", (req, res) => {
  UserModel.deleteOne({
    _id: req.params.myid
  }).then(data => {
    res.send({ //返回客户端数据
      ok: 1
    })
  })
})

//------获取列表 (列表数据渲染)------  
router.get("/user/list", (req, res) => {
  const { page, limit } = req.query //获取第几页 、 多少条数据
  UserModel.find({}, ["username", "age"]).sort({ age: -1 }).skip((page - 1) * limit).limit(limit).then(data => {
    res.send(data)
  })
})

    第四步 规范使用 Mongodb命令 (RESTful架构)

客户端

<!DOCTYPE html>
<html>

<head>
  <title>登录客户端</title>
</head>

<body>
  <h1>mongodb的增删改查的演示</h1>
  <div>
    <div>用户名:<input id="username" /></div>
    <div>密码:<input type="password" id="password" /></div>
    <div>年龄:<input type="number" id="age" /></div>
    <div><button id="register">注册</button></div>
  </div>
  <hr>
  <div>
    <button id="update">更新</but ton>
      <button id="delete">删除</button>
  </div>
  <hr>

  <table border="1">
    <thead>
      <tr>
        <td>id</td>
        <td>用户名</td>
        <td>年龄</td>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
  <script>

    var register = document.querySelector("#register")
    var update = document.querySelector("#update")
    var deletebutton = document.querySelector("#delete")
    var username = document.querySelector("#username")
    var password = document.querySelector("#password")
    var age = document.querySelector("#age")

    register.onclick = () => {
      fetch("/api/user", {
        method: "POST",
        body: JSON.stringify({
          username: username.value,
          password: password.value,
          age: age.value
        }),
        headers: {
          "Content-Type": "application/json"
        }
      }).then(res => res.json()).then(res => {
        console.log(res)
      })
    }

    update.onclick = () => {
      fetch("/api/user/?", {
        method: "PUT",
        body: JSON.stringify({
          username: "修改的名字",
          password: "修改的密码",
          age: 1
        }),
        headers: {
          "Content-Type": "application/json"
        }
      }).then(res => res.json()).then(res => {
        console.log(res)
      })
    }

    deletebutton.onclick = () => {
      fetch("/api/user/?", {
        method: "DELETE"
      }).then(res => res.json()).then(res => {
        console.log(res)
      })
    }

    //获取列表
    fetch("/api/user?page=1&limit=10").then(res => res.json()).then(res => {
      var tbody = document.querySelector("tbody")
      tbody.innerHTML = res.map(item => `
          <tr>
            <td>${item._id}</td>  
            <td>${item.username}</td>  
            <td>${item.age}</td>  
          </tr>
        `).join("")
    })
  </script>
</body>

</html>

服务器

//相应前端的post请求-增加用户
router.post("/user", (req, res) => {
  const { username, password, age } = req.body
  UserModel.create({
    username, password, age
  }).then(data => {
    console.log(data) //成功获取的数据
    res.send({ //返回客户端数据
      ok: 1
    })
  })
})

//------用户修改数据接口 (更新数据)------  
//动态路由, 获取ID
router.put("/user/:myid", (req, res) => {
  const { username, age, password } = req.body
  UserModel.updateOne({ _id: req.params.myid }, {
    username, age, password
  }).then(data => {
    res.send({//返回客户端数据
      ok: 1
    })
  })
})

//------用户删除数据接口 (删除数据)------  
router.delete("/user/:myid", (req, res) => {
  UserModel.deleteOne({
    _id: req.params.myid
  }).then(data => {
    res.send({//返回客户端数据
      ok: 1
    })
  })
})

//------获取列表 (列表数据渲染)------  
router.get("/user", (req, res) => {
  const { page, limit } = req.query
  UserModel.find({}, ["username", "age"]).sort({ age: -1 }).skip((page - 1) * limit).limit(limit).then(data => {
    res.send(data)
  })
})

总结

以上是个人学习Node的相关知识点,一点一滴的记录了下来,有问题请评论区指正,共同进步,这才是我写文章的原因之,如果这篇文章对您有帮助请三连支持一波

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2023年6月10日
下一篇 2023年6月10日

相关推荐