のことで
+----+--------+-----+
| id | name | age |
+----+--------+-----+
| 1 | Tanaka | 22 |
| 2 | Yamada | 30 |
| 3 | Sato | 27 |
+----+--------+-----+const users = new Users()
connection.query('SELECT * from userdata', (err, rows) => {
for(const { id, name } of rows) {
const user = new User(id, name)
users.add(user)
}
})
console.log(users.users)
/*
[
{ id: 1, name: 'Tanaka', age: 22 },
{ id: 2, name: 'Yamada', age: 30 },
{ id: 3, name: 'Sato', age: 27 }
]
*/+----+--------+-----+
| id | name | age |
+----+--------+-----+
| 1 | Tanaka | 22 |
| 2 | Yamada | 30 |
| 3 | Sato | 27 |
+----+--------+-----+const users = model.user.findAll()
console.log(users)
/*
[
{ id: 1, name: 'Tanaka', age: 22 },
{ id: 2, name: 'Yamada', age: 30 },
{ id: 3, name: 'Sato', age: 27 }
]
*/CREATE TABLE "public"."User" (
id SERIAL PRIMARY KEY NOT NULL,
name VARCHAR(255),
age INTEGER NOT NULL
);generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
name String?
age Int
}prisma.user.create({
data: {
name: 'Suzuki',
gender: 'male' // 性別は存在しないプロパティなので怒られる
}
})
model User {
id Int @id @default(autoincrement())
name String?
age Int
}$ npm init -y # npm の初期化
$ npm i @prisma/cli @prisma/client # prisma のインストール
$ npx prisma init # prisma の初期化
$ npm i -D typescript # typescript のインストール
$ npx tsc --init # typescript の初期化{
"target": "ESNEXT",
"moduleResolution": "node"
}tsconfig.json の設定
$ touch docker-compose.yml # dcoker-compose ファイルの作成version: '3'
services:
db:
image: postgres:12.2-alpine
container_name: db-container
ports:
- "5432:5432"
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=mysecretpassword1234
- POSTGRES_DB=testdb
- DATABASE_HOST=localhost
volumes:
- ./docker/db/init:/docker-entrypoint-initdb.ddocker-compose.yml の設定
$ docker-compose up # DB の構築&起動DATABASE_URL="postgresql://postgres:mysecretpassword1234@localhost:5432/testdb?schema=public".env の設定
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
name String?
age Int
}prisma/schema.prisma の設定
$ npx prisma migrate dev --preview-feature # マイグレーション$ npx prisma generateimport { PrismaClient } from "@prisma/client"
const prisma = new PrismaClient()
async function main() {
// データベースからすべてのユーザーレコードを読み取り出力
const allUsers = await prisma.user.findMany()
console.log(allUsers)
}
main()
.catch(e => {
throw e
})
.finally(async () => {
await prisma.$disconnect()
})index.ts の設定
$ touch index.ts$ npx ts-node index.ts