docker desktopMongoDB配置并用NodeJS连接
Posted _less is more
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了docker desktopMongoDB配置并用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进行查看数据
以上是关于docker desktopMongoDB配置并用NodeJS连接的主要内容,如果未能解决你的问题,请参考以下文章