LoginSignup
0
0

More than 3 years have passed since last update.

docker: mongodb

Last updated at Posted at 2020-07-12

image

terminal
docker pull mongo

localhost:27017でDBに接続する場合

docker

terminal
# launch
docker run --name mongodb -p 27017:27017 -v `pwd`/db:/data/db -d mongo

# stop
docker rm -f mongodb

# shell
docker exec -it mongodb mongo

docker-compose

docker-compose.yml
version: '3.8'
services:
  db:
    image: mongo
    container_name: mongodb
    ports:
      - 27017:27017
    volumes:
      - ./db:/data/db
terminal
# launch
docker-compose up

# stop
docker-compose down

他のdockerコンテナから直接アクセスする場合

例、dockerコンテナで動くnode.jsアプリ(localhost:3000でアクセス)から、mongodbに、mongodb://db:27017 でアクセスする

docker-compose

docker-compose.yml
version: '3.8'
services:
  web:
    image: node:alpine
    working_dir: /home/node/app
    volumes:
      - ./:/home/node/app
    ports:
      - 3000:3000
    command: ash -c "npm run build && npm start"
  db:
    image: mongo #portsの指定は不要.
    volumes:
      - ./db:/data/db
terminal
# launch
docker-compose up

# stop
docker-compose down
サンプルコード.ts
import { MongoClient, Collection } from 'mongodb'

const URL = 'mongodb://db:27017'
const NAME = 'mongodb'

export async function insertDocument(collectionName: string, document: object) {
  await crudCollection(
    collectionName,
    async (collection) => await collection.insertOne(document)
  )
}

export async function findDocuments(
  collectionName: string,
  filter: object
): Promise<any[]> {
  return await crudCollection(
    collectionName,
    async (collection) => await collection.find(filter).toArray()
  )
}

export async function updateDocument(
  collectionName: string,
  filter: object,
  newDocument: object
) {
  await crudCollection(
    collectionName,
    async (collection) =>
      await collection.updateOne(filter, { $set: newDocument })
  )
}

export async function deleteDocument(collectionName: string, filter: object) {
  await crudCollection(
    collectionName,
    async (collection) => await collection.deleteOne(filter)
  )
}

/**
 * @private
 */
async function crudCollection(
  collectionName: string,
  method: (collection: Collection<any>) => Promise<any>
) {
  let client: MongoClient
  try {
    client = await MongoClient.connect(URL, { useNewUrlParser: true })
    const collection = client.db(NAME).collection(collectionName)
    return await method(collection)
  } finally {
    client.close()
  }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0