“ node.js后端+小程序前端+mongoDB(增删改查) ”

发布时间:2024-02-06
今日阅读:0
来源:CSDN
作者:淼学派对
...

前言

今天我对比了以下node.js的express与python的fastAPI,我决定我还是出一期关于node.js+mangoDB+小程序的小案例吧。 不是python的fastAPI不好用,因为fastAPI是python较新的技术,我不敢果断发出教学文章这件事情还是留着给python大佬们叭~

技术栈

  • node.js
  • 微信小程序
  • JavaScript
  • mongoDB
  • expressnode.js web框架
  • mongoosemongoDB管理器

    mongDB优点

    灵活的数据模型 MongoDB是一个文档型数据库,使用BSONBinary JSON格式存储数据。这种文档型结构使得存储的数据可以非常灵活,可以包含不同类型的数据和嵌套结构,适合处理复杂的数据模型。 横向扩展水平扩展 MongoDB支持横向扩展,可以通过添加更多的节点来提高性能和容量。这种能力使得MongoDB在处理大规模数据和高负载时表现出色。 高性能 MongoDB采用了索引、聚合框架和内置分片等技术,以提供高性能的数据查询和检索。它还具有内置的缓存机制,能够有效地减轻数据库的负载。 自动分片Sharding MongoDB支持自动分片,可以将大型数据集水平划分成小块,分布在多个服务器上。这有助于提高查询性能和负载均衡。 丰富的查询语言 MongoDB提供强大而灵活的查询语言,支持各种条件查询、范围查询、正则表达式等。同时,它还支持索引,加速查询操作。 容易扩展和管理 安装、配置和使用MongoDB相对较简单。它提供了直观的命令行工具和管理界面,使得数据库的维护和监控变得更加容易。 JSON风格的文档 MongoDB的文档采用JSON风格的格式,这使得数据在应用程序和数据库之间的映射更为自然。这种文档存储的方式也使得数据更易于理解和使用。 社区支持和活跃 MongoDB有一个庞大的开源社区,提供了丰富的文档、教程和问题解答。这种活跃的社区支持使得开发者能够更容易找到解决问题的方法。

    node.js优点

    高性能 Node.js采用了非阻塞的I/O模型,使得它能够处理大量并发连接而不会造成阻塞。这使得Node.js在处理I/O密集型任务时表现出色,能够实现更高的吞吐量和更低的响应时间。 快速开发 Node.js使用JavaScript作为开发语言,这使得前端和后端开发都可以使用同一种语言,简化了开发人员的学习曲线和开发工作流程。此外,Node.js的模块化设计和丰富的第三方模块库也有助于快速开发和构建应用。 轻量和高效 Node.js本身是一个轻量级的运行时环境,占用资源较少,启动时间短。这使得它适用于构建高效的后端服务和微服务架构。 生态系统丰富 Node.js拥有庞大而活跃的开源生态系统,包括npmNode Package Manager上数以万计的可重用模块。开发人员可以通过npm轻松地引入和管理依赖项,加快开发速度并提高代码质量。 支持异步编程 Node.js基于事件驱动和非阻塞I/O模型,支持异步编程风格。这使得开发人员能够编写高效的、非阻塞的代码,从而更好地利用系统资源并提高应用的响应能力。 跨平台 Node.js可以在多个平台上运行,包括Windows、macOS和各种Linux发行版。这使得开发人员能够轻松地在不同的操作系统上开发和部署应用。 社区支持和活跃 Node.js拥有一个庞大而活跃的社区,提供了丰富的文档、教程和问题解答。这使得开发人员能够更容易地获取帮助、分享经验并解决问题。 可伸缩性 由于Node.js采用了事件驱动和非阻塞I/O模型,它非常适合构建高性能、可伸缩的应用。开发人员可以根据需要轻松地扩展应用,满足不断增长的用户需求。

    mongoDB下载

    Install MongoDB Community Kubernetes Operator | MongoDB 新的mongoDB版本自带可视化工具

    安装指令

    1. 下载node.js框架 npm install express –save
  • 下载nodemon解决node代码更新的痛点 npm install nodemon -g

  • node.js连接mongodb数据库 npm install mongoose –save

    后端目录

    img

    db.js

    const mongoose = require('mongoose')
    //连接mongodb数据库
    mongoose.connect("mongodb://localhost:27017/node_one")
    .then(() => {
        console.log("数据库连接成功!")
    })
    .catch((err) => {
        console.log("数据库连接失败!", err)
    })
    // 创建表
    const LoseSchema = new mongoose.Schema({
    name: {
        type: String,
    },
    nianling: {
        type: String
    },
    })
    const Lose = mongoose.model("LoseSchema", LoseSchema);
    module.exports = {
    Lose
    }
    

    index.js

    const express = require('express');
    const app = express();
    const { Lose } = require('./db');
    app.use(express.urlencoded({ extended: true }));
    app.use(express.json())
    // 增加数据
    app.post("/publish", async (req, res) => {
    try {
        const { name, nianling } = req.body;
        await Lose.create({
            name, nianling
        });
        res.send("success")
    } catch (error) {
        res.send(error, "error")
    }
    })
    // 删除指定数据
    app.post("/del", async (req, res) => {
    console.log(req.body.name)
    try {
        const { name } = req.body;
        // 使用 deleteOne 删除指定 name 的数据
        const result = await Lose.deleteOne({ name });
        if (result.deletedCount === 1) {
            res.send("success");
        } else {
            res.send("未找到匹配的记录");
        }
    } catch (error) {
        res.send(error, "error");
    }
    })
    // 修改指定数据
    app.post("/upd", async (req, res) => {
    try {
        const { name, newNianling } = req.body;
        // 使用 updateOne 更新指定 name 的数据记录的 nianling 字段
        const result = await Lose.updateOne({ name }, { $set: { nianling: newNianling } });
        if (result.nModified === 1) {
            res.send("success");
        } else {
            res.send("未找到匹配的记录或未进行任何修改");
        }
    } catch (error) {
        res.send(error, "error");
    }
    });
    // 查询指定数据
    app.get("/find/:name", async (req, res) => {
    try {
        const name = req.params.name;
        // 使用 find 查询所有匹配指定 name 的数据记录
        const results = await Lose.find({ name });
        if (results.length > 0) {
            // 如果找到匹配的记录,则返回所有匹配的记录
            res.json(results);
        } else {
            res.send("未找到匹配的记录");
        }
    } catch (error) {
        res.send(error, "error");
    }
    });
    app.listen(3000, () => {
    console.log('server running')
    })
    

    小程序

    index1.js

    // pages/index1/index1.js
    Page({
    /**
    * 页面的初始数据
    */
    data: {
    },
    // 增加
    // 输入框1的输入事件(姓名)
    input1Change(e) {
    this.setData({
      inputValue1: e.detail.value,
    });
    },
    // 输入框2的输入事件年龄
    input2Change(e) {
    this.setData({
      inputValue2: e.detail.value,
    });
    },
    tijiao(){
    wx.request({
      url: 'http://localhost:3000/publish',
      method:'POST',
      data:{
        name:this.data.inputValue1,
        nianling:this.data.inputValue2
      },
    })
    },
    // 删除
    input1Change_del(e){
    this.setData({
      inputValue_del: e.detail.value,
    });
    },
    shanchu(){
    wx.request({
      url: 'http://localhost:3000/del',
      method:'POST',
      data:{
        name:this.data.inputValue_del,
      },
    })
    },
    // 修改
    input1Change_upd(e){
    this.setData({
      inputValue1_upda: e.detail.value,
    });
    },
    input2Change_upd(e){
    this.setData({
      inputValue2_upda: e.detail.value,
    });
    },
    xiugai(){
    wx.request({
      url: 'http://localhost:3000/upd',
      method:'POST',
      data:{
        // 名字
        name:this.data.inputValue1_upda,
        // 修改后的年龄
        newNianling:this.data.inputValue2_upda,
      },
    })
    },
    // 查询
    input1Change_find(e){
    this.setData({
      inputValue1_find: e.detail.value,
    });
    },
    find(){
    wx.request({
      url: 'http://localhost:3000/find/' + this.data.inputValue1_find,
      method: 'GET',
      success: function(res) {
        // 请求成功,处理从服务器返回的数据
        console.log('服务器返回的数据', res.data);
      
        // 检查是否找到匹配的记录
        if (res.data && res.data.length > 0) {
          // 处理返回的记录数据
          const records = res.data;
          records.forEach(record => {
            console.log('记录:', record);
            // 在这里进行您的处理逻辑,例如显示在界面上
          });
        } else {
          console.log('未找到匹配的记录');
          // 在界面上显示相应的消息,告知用户未找到匹配的记录
        }
      },
      fail: function(error) {
        // 请求失败,处理错误
        console.error('请求失败:', error);
        // 在界面上显示错误信息,告知用户请求失败
      }
    });
    },
    /**
    * 生命周期函数--监听页面加载
    */
    onLoad(options) {
    },
    /**
    * 生命周期函数--监听页面初次渲染完成
    */
    onReady() {
    },
    /**
    * 生命周期函数--监听页面显示
    */
    onShow() {
    },
    /**
    * 生命周期函数--监听页面隐藏
    */
    onHide() {
    },
    /**
    * 生命周期函数--监听页面卸载
    */
    onUnload() {
    },
    /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
    onPullDownRefresh() {
    },
    /**
    * 页面上拉触底事件的处理函数
    */
    onReachBottom() {
    },
    /**
    * 用户点击右上角分享
    */
    onShareAppMessage() {
    }
    })
    

index1.wxml

<!-- 添加姓名与年龄 -->
<view class="container">
  <view>
    <text>请输入第一个值</text>
    <input placeholder="输入框1" bindinput="input1Change" />
  </view>
  <view>
    <text>请输入第二个值</text>
    <input placeholder="输入框2" bindinput="input2Change" />
  </view>
  <button bindtap="tijiao">增加</button>
</view>
<!-- 根据指定字段姓名删除数据记录 -->
<view class="container">
  <view>
    <text>请输入第一个值</text>
    <input placeholder="输入框1" bindinput="input1Change_del" />
  </view>
  <button bindtap="shanchu">删除</button>
</view>
<!-- 根据指定字段姓名修改数据记录 -->
<view class="container">
  <view>
    <text>请输入第一个值</text>
    <input placeholder="名字" bindinput="input1Change_upd" />
  </view>
  <view>
    <text>请输入第一个值</text>
    <input placeholder="修改后的年龄" bindinput="input2Change_upd" />
  </view>
  <button bindtap="xiugai">修改</button>
</view>
<!-- 根据指定字段姓名修改数据记录 -->
<view class="container">
  <view>
    <text>请输入第一个值</text>
    <input placeholder="名字" bindinput="input1Change_find" />
  </view>
  <button bindtap="find">查询</button>
</view>

index1.wxss

/* inputPage.wxss */
.container {
  padding: 20rpx;
}
text {
  font-size: 16rpx;
  margin-right: 10rpx;
}
input {
  height: 30rpx;
  border: 1rpx solid #ccc;
  padding: 5rpx;
  margin-bottom: 10rpx;
}
button {
  width: 200rpx;
  background-color: #4CAF50;
  color: #fff;
  border: none;
  border-radius: 5rpx;
}

每日一言

""男人单身叫单身狗,女的单身叫狗不理。""

...

站点统计

本周更新文章: 0 篇
文章总数: 59110 篇
今日访问量: 38277 次
访问总量: 149600 次