typescript mongodb helloworld

  1. make project dir

    mkdir sample

  2. open vscode

    code sample

  3. make docker-compose.yml

docker-compose.yml

```
version: "3"
services:
  app:
    image: node
    volumes:
      - .:/app
    working_dir: /app
    depends_on:
      - mongo
    tty: true
  mongo:
    image: mongo
    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
```
  1. npm init

    sudo docker-compose run -u (id -u $USER):(id -g $USER) app npm init -y

  2. npm install

    sudo docker-compose run -u (id -u $USER):(id -g $USER) app npm install -D typescript ts-node

  3. tsc init

    sudo docker-compose run -u (id -u $USER):(id -g $USER) app npx tsc --init --target ES2020

  4. npm install

    sudo docker-compose run -u (id -u $USER):(id -g $USER) app npm install mongodb @types/mongodb --save

  5. docker run

    sudo docker-compose up -d

  6. setup mongo db

    http://localhost:8081/

    Screenshot_2020-05-23 Home - Mongo Express(1).png (91.8 kB)

    Screenshot_2020-05-23 sandbox - Mongo Express.png (65.8 kB)

  7. create index.ts file

index.ts

```
import mongodb, { MongoClient } from "mongodb";

(async () => {
  const MongoClient = mongodb.MongoClient;
  const url = "mongodb://root:example@mongo:27017";
  const dbName = "sandbox";
  const connectOption = {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  };

  const client = await MongoClient.connect(url, connectOption);
  const db = client.db(dbName);

  const collection = db.collection("hello")
  await collection.insertOne({ title: "hello", content: "hello" });
  await collection.insertMany([
    { title: "hello_1", content: "hello_1" },
    { title: "hello_2", content: "hello_2" },
  ]);
  await collection.updateOne({ title: "hello_1" }, { $set: { content: "hello changed" } });

  const helloCollection = await collection.find({}).toArray();
  for (let i = 0; helloCollection.length > i; i++) {
    const hello = helloCollection[i];
    console.log(hello);
  }

  await collection.deleteMany({});

  await client.close();
})();
```
  1. edit package.json file

    package.json

    "start": "ts-node index.ts",

  2. npm start

    sudo docker-compose exec app npm start

https://hub.docker.com/_/mongo