• 【docker desktop】MongoDB配置并用NodeJS连接


    1、创建mongo:5容器

    docker run --rm -d -p 27017:27017 mongo:5
    

    这里不能用-it /bin/bash,而且得加上-d使之后台运行,然后再进去,不然会报错Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused

    从外面进入容器

    docker exec -it 26d83e6bb443 /bin/bash
    

    2、进入mongo

    在容器里键入

    mongo
    

    3、查看数据库

    show dbs
    

    4、进入数据库

    use test
    

    如果test数据库不存在,则自动创建

    5、查看表

    show collections
    

    6、像表中插入内容

    db.class.insert({'name':'ee547'})
    

    如果名为class的表单不存在则自动创建

    7、查看表中内容

    > db.class.find()
    { "_id" : ObjectId("632a16e412de6627982e581b"), "name" : "ee547" }
    

    8、删除数据库
    在test数据库中,使用如下命令

    db.dropDatabase()
    

    则会删除当前正在使用的数据库

    9、连接MongoDB环境介绍

    IDE:VScode
    REST请求:REST Client(extensions on VScode
    MongoDB:在Docker Desktop中
    MongoDB url:mongodb://127.0.0.1:27017/

    NodeJS项目目录结构:
    在这里插入图片描述
    主要有三个js文件,以及一个.rest的REST Client文件,便于快速方便地请求REST api,代码如下

    routes/route.rest,实现了增删改查的接口请求

    ###
    GET http://localhost:3000/subscribers
    
    ###
    
    POST http://localhost:3000/subscribers/
    Content-Type: application/json
    
    {
        "name": "USC",
        "subscribedToChannel": "Department of ECE"
    }
    
    
    ###
    GET http://localhost:3000/subscribers/63242fedb5c65a78db2ecb6e
    
    
    ###
    PATCH http://localhost:3000/subscribers/6324ed272190b93d2139c779
    Content-Type: application/json
    
    {
        "name": "New Name"
    }
    
    
    ### 
    DELETE http://localhost:3000/subscribers/6324d73c1ed76bb99b45f659
    

    server.js

    require('dotenv').config()
    
    const express = require('express')
    const app = express()
    const mongoose = require('mongoose')
    
    mongoose.connect('mongodb://127.0.0.1:27017/', { useNewUrlParser: true })
    const db = mongoose.connection
    db.on('error', (error) => console.error(error))
    db.once('open', () => console.log('Connected to Database'))
    
    app.use(express.json())
    
    const subscribersRouter = require('./routes/subscribers')
    app.use('/subscribers', subscribersRouter)
    
    app.listen(3000, () => console.log('Server Started'))
    

    routes/subscribers.js

    const express = require('express')
    const router = express.Router()
    const Subscriber = require('../models/subscriber')
    
    // Getting all
    router.get('/', async (req, res) => {
      try {
        const subscribers = await Subscriber.find()
        res.json(subscribers)
      } catch (err) {
        res.status(500).json({ message: err.message })
      }
    })
    
    // Getting One
    router.get('/:id', getSubscriber, (req, res) => {
      res.json(res.subscriber)
    })
    
    // Creating one
    router.post('/', async (req, res) => {
      const subscriber = new Subscriber({
        name: req.body.name,
        subscribedToChannel: req.body.subscribedToChannel
      })
      try {
        const newSubscriber = await subscriber.save()
        res.status(201).json(newSubscriber)
      } catch (err) {
        res.status(400).json({ message: err.message })
      }
    })
    
    // Updating One
    router.patch('/:id', getSubscriber, async (req, res) => {
      if (req.body.name != null) {
        res.subscriber.name = req.body.name
      }
      if (req.body.subscribedToChannel != null) {
        res.subscriber.subscribedToChannel = req.body.subscribedToChannel
      }
      try {
        const updatedSubscriber = await res.subscriber.save()
        res.json(updatedSubscriber)
      } catch (err) {
        res.status(400).json({ message: err.message })
      }
    })
    
    // Deleting One
    router.delete('/:id', getSubscriber, async (req, res) => {
      try {
        await res.subscriber.remove()
        res.json({ message: 'Deleted Subscriber' })
      } catch (err) {
        res.status(500).json({ message: err.message })
      }
    })
    
    async function getSubscriber(req, res, next) {
      let subscriber
      try {
        subscriber = await Subscriber.findById(req.params.id)
        if (subscriber == null) {
          return res.status(404).json({ message: 'Cannot find subscriber' })
        }
      } catch (err) {
        return res.status(500).json({ message: err.message })
      }
    
      res.subscriber = subscriber
      next()
    }
    
    module.exports = router
    

    models/subscriber.js

    const mongoose = require('mongoose')
    
    const subscriberSchema = new mongoose.Schema({
      name: {
        type: String,
        required: true
      },
      subscribedToChannel: {
        type: String,
        required: true
      },
      subscribeDate: {
        type: Date,
        required: true,
        default: Date.now
      }
    })
    
    module.exports = mongoose.model('Subscriber', subscriberSchema)
    

    用node server.js启动服务,然后到route.rest文件下尝试不同命令(需要提前安装REST Client这个extension,直接点击Send Request即可请求
    在这里插入图片描述
    然后可以回到docker里的mongodb进行查看数据
    在这里插入图片描述

  • 相关阅读:
    电子学会2022年6月青少年软件编程(图形化)等级考试试卷(一级)
    半导体电学特性IV+CV测试系统—1200V半导体参数分析仪
    opencv特征增强,纺射变幻,模糊,锐化,翻转
    2-4:HTTP的九种请求方法介绍,设计接口的时候到底该采用哪种请求方式?
    第L6周:机器学习-随机森林(RF)
    HTML5期末大作业:动漫网站设计——神偷奶爸(10页) HT简单个人网页设计作业 静态动漫主题网页作业 DW个人网站模板下载
    rm -rf 真是删库跑路的一把好手
    ssm162基于SSM的药房药品采购集中管理系统的设计与实现+vue
    H5点击复制功能 兼容安卓、IOS
    KNN算法推理与实现
  • 原文地址:https://blog.csdn.net/weixin_42815846/article/details/126964857