make project dir
mkdir sample
open vscode
code sample
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
```
npm init
sudo docker-compose run -u (id -u $USER):(id -g $USER) app npm init -y
npm install
sudo docker-compose run -u (id -u $USER):(id -g $USER) app npm install -D typescript ts-node
tsc init
sudo docker-compose run -u (id -u $USER):(id -g $USER) app npx tsc --init --target ES2020
npm install
sudo docker-compose run -u (id -u $USER):(id -g $USER) app npm install mongodb @types/mongodb --save
docker run
sudo docker-compose up -d
setup mongo db
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();
})();
```