ติดตั้ง mongo ด้วย docker
docker run --name wrk-mongo -p 2888:27017 -d mongo --auth
จากนั้นตรวจสอบ ด้วยคำสั่ง
docker ps
![](https://thana.in.th/wp-content/uploads/2020/05/Screen-Shot-2563-05-29-at-00.35.42-1024x215.png)
จะแสดง container ขึ้นมาแปลว่าได้ mongo มาละ เจ๋งป่ะล่ะ docker บรรทัดเดียวได้ db แว้ววว
จากนั้นเราก็เข้าไปสร้าง user root โดยเข้าสร้างใน container
docker exec -it wrk-mongo mongo admin
![](https://thana.in.th/wp-content/uploads/2020/05/Screen-Shot-2563-05-29-at-00.42.02-1024x198.png)
db.createUser({
user: "admin",
pwd: "secure",
roles: [ { role: "root", db: "admin" } ]
})
![](https://thana.in.th/wp-content/uploads/2020/05/Screen-Shot-2563-05-29-at-00.45.44.png)
จากนั้นก็ออกด้วย
exit
เข้ามาใหม่ด้วย user admin
docker exec -it wrk-mongo bash
![](https://thana.in.th/wp-content/uploads/2020/05/Screen-Shot-2563-05-29-at-01.06.55-1024x59.png)
mongo -u admin -p secure --authenticationDatabase admin
![](https://thana.in.th/wp-content/uploads/2020/05/Screen-Shot-2563-05-29-at-01.08.03-1024x299.png)
ทดสอบคำสั่ง
show dbs
![](https://thana.in.th/wp-content/uploads/2020/05/Screen-Shot-2563-05-29-at-01.08.47.png)
จากนั้นก็สร้าง db ชื่อว่า test
use test
![](https://thana.in.th/wp-content/uploads/2020/05/Screen-Shot-2563-05-29-at-01.09.48.png)
เพิ่ม record ไปยัง collection products
db.products.insert({
name: 'iPhone11',
category: 'Mobile',
price: '48000'
})
![](https://thana.in.th/wp-content/uploads/2020/05/Screen-Shot-2563-05-29-at-01.12.14.png)
db.products.find()
![](https://thana.in.th/wp-content/uploads/2020/05/Screen-Shot-2563-05-29-at-01.15.07-1024x62.png)
db.createUser({
user: "usr",
pwd: "secure",
roles: [ { role: "readWrite", db: "test" } ]
})
![](https://thana.in.th/wp-content/uploads/2020/05/Screen-Shot-2563-05-29-at-01.16.03.png)
จากนั้นก็ออกด้วย
exit
เราจะใช้ Nodejs ทดสอบดังนี้
const express = require('express')
const app = express()
const mongoose = require('mongoose')
const Product = require('./product')
const products = [{}]
app.use(express.json())
mongoose.connect('mongodb://usr:secure@localhost:2888/test', { useNewUrlParser: true })
app.get('/', (req, res) => {
res.json({ message: 'wrk-mongodb!' })
})
app.get('/products', async (req, res) => {
const products = await Product.find({})
res.json(products)
})
app.listen(9000, () => {
console.log('Application is running on port 9000')
})
ซึ่ง connection string ก็ตามนี้
mongoose.connect('mongodb://usr:secure@localhost:2888/test', { useNewUrlParser: true })
ตัดจบล่ะ ไปดูรายละเอียดใน youtube ละกัน
(Visited 911 times, 1 visits today)