14.12.1. 使用mongoose访问mongodb
14.12.1.1. docker运行mongodb
在项目目录中创建docker-compose.yaml文件,内容如下:
version: '3.1'
services:
mongo:
image: mongo
restart: always
ports:
- 27017:27017
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
mongo-express:
image: mongo-express
restart: always
ports:
- 8081:8081
environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: root
ME_CONFIG_MONGODB_ADMINPASSWORD: example
ME_CONFIG_MONGODB_URL: mongodb://root:example@mongo:27017/
注意
端口别和宿主机上的端口冲突了。
启动
docker compose up
14.12.1.2. 连接mongo,并创建账号
mongo -u root -p example
>use ktv
>db.createUser({
user: "ktv",
pwd: "123456",
roles: [
{ role: "readWrite", db: "ktv-select_music_system" }
]
})
14.12.1.3. mongoose连接
mongoose.connect('mongodb://ktv:123456@localhost:27017/ktv-select_music_system')