nodejs数据持久化--MongoDB(2)案例实现

project
│ index.html
│ index.js
└─model
  │ conf.js
  └─db.js

数据库配置参数 conf.js

module.exports = {
  // 数据库地址
  url: 'mongodb://localhost:27017',
  // 数据库名称
  dbName: 'test'
}

数据库配置 db.js

const conf = require('./conf')

const EventEmitter = require('events').EventEmitter

// 客户端
const MongoClient = require('mongodb').MongoClient

class Mongodb {
  constructor(conf) {
    // 保存
    this.conf = conf
    this.emitter = new EventEmitter

    // 连接
    this.client = new MongoClient(conf.url, {
      useNewUrlParser: true
    })

    this.client.connect(err => {
      if (err) throw err
      console.log('连接成功')
      this.emitter.emit('connect')
    })
  }

  // 数据库对象
  col(colName, dbName = conf.dbName) {
    return this.client.db(dbName).collection(colName)
  }

  // 执行一次
  once(event, cb) {
    this.emitter.once(event, cb)
  }
}

module.exports = new Mongodb(conf)

实现数据接口

const express = require('express')
const app = express()
const path = require('path')
const mongo = require('./model/db')

app.get('/', (req, res) => {
  res.sendFile(path.resolve(__dirname, './index.html'))
})

// 搜索
app.get('/api/category', async (req, res) => {
  const col = mongo.col('fruits')
  const data = await col.distinct('category')
  res.json({
    ok: 1,
    data
  })
})

// 列表
app.get('/api/list', async (req, res) => {
  // 分页查询
  const { page = 1, category, keyword } = req.query || {}
  // 构造条件
  const condition = {}
  if (category) {
    condition.category = category
  }
  if (keyword) {
    condition.name = {
      $regex: new RegExp(keyword)
    }
  }
  try {
    const col = mongo.col('fruits')
    const total = await col.find(condition).count()
    const fruits = await col.find(condition).skip((page - 1) * 5).limit(5).toArray()
    res.json({
      ok: 1,
      data: {
        fruits,
        pagination: {
          total: total
        }
      }
    })
  } catch (error) {
    console.log(error)
  }
})

app.listen(3000, () => {
  console.log('listening at 3000')
})

前端页面 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css" />
  <title>购物车实战</title>
</head>
<body>
  <div id="app">
    <el-input placeholder="请输入内容" v-model="search" class="input-with-select"  @change="changeHandler">
      <el-button slot="append" icon="el-icon-search"></el-button>
    </el-input>
    <el-radio-group v-model="category" @change="getData">
      <el-radio-button v-for="v in categorys" :label="v" :key="v">{{v}}</el-radio-button>
    </el-radio-group>
    <el-table :data="fruits" style="width: 100%">
      <el-table-column prop="name" label="名称" width="180">
      </el-table-column>
      <el-table-column prop="price" label="价格" width="180">
      </el-table-column>
      <el-table-column prop="category" label="种类">
      </el-table-column>
    </el-table>
    <el-pagination layout="prev, pager, next" @current-change="currentChange" :total="total">
    </el-pagination>
  </div>
  <script>
    const app = new Vue({
      el: '#app',
      data() {
        return {
          page: 1,
          total: 0,
          fruits: [],
          categorys: [],
          category: [],
          search:''
        }
      },
      created() {
        this.getData()
       this.getCategory()
      },
      methods: {
      	// 分页
        async currentChange(page) {
          this.page = page
          await this.getData()
        },
        // 搜索
        async changeHandler(val) {
          this.search = val
          await this.getData()
        },
        // 获取数据
        async getData() {
          const res = await axios.get(`/api/list?page=${this.page}&category=${this.category}&keyword=${this.search}`)
          const data = res.data.data
          this.fruits = data.fruits
          this.total = data.pagination.total
        },
        // 获取类型
        async getCategory() {
          const res = await axios.get(`/api/category`)
          this.categorys = res.data.data
        }
      }
    })
  </script>
</body>
</html>

执行结果
在这里插入图片描述

Docker是一种容器化解决方案,Docker Compose可以简化多个容器的管理和部署流程。Nacos是一个用于服务发现、配置管理和动态DNS服务的开源平台。Node.js是一个基于JavaScript的开源、跨平台的运行时环境,用于构建可扩展的网络应用程序。MongoDB是一个高性能、文档型NoSQL数据库,适用于处理大量的结构化和非结构化数据。MySQL是一个开源的关系型数据库管理系统,用于存储和管理结构化数据。Redis是一个基于内存的高性能键值存储系统,用于缓存和数据持久化。Seata是一个开源的分布式事务解决方案,用于保证分布式系统中的数据一致性。 通过Docker Compose,我们可以轻松地将这些不同的组件和服务以容器化的方式部署在一台或多台服务器上。我们可以使用Docker Compose的配置文件定义每个服务的镜像、端口映射、环境变量等设置。在这个场景中,我们可以将Nacos、Node.js、MongoDB、MySQL、Redis和Seata分别作为独立的服务进行定义。 使用Docker Compose可以简化部署过程,只需运行一个命令即可启动整个应用程序的容器群组。Docker会自动拉取和部署所需的镜像,启动容器,并通过网络连接各个服务。Nacos可以作为服务发现和配置中心,用于管理和注册各个服务的地址和配置信息。Node.js可以作为应用程序的后端逻辑进行开发,通过Nacos来发现和调用各个后端服务。MongoDB作为主要的数据存储,MySQL和Redis可以作为辅助数据存储和缓存。Seata可以用于管理和控制分布式事务,确保数据一致性。 总之,使用Docker Compose可以方便地将Nacos、Node.js、MongoDB、MySQL、Redis和Seata等组件集成在一起,并通过容器化的方式进行部署。这样做可以极大地简化应用程序的开发和部署过程,并提供高度可扩展的架构。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值