
- TypeORM 教程
- TypeORM - 主頁
- TypeORM - 介紹
- TypeORM - 安裝
- TypeORM - 建立一個簡單的專案
- TypeORM - 連線 API
- TypeORM - 實體
- TypeORM - 關係
- TypeORM - 使用儲存庫
- TypeORM - 使用實體管理器
- TypeORM - 查詢構建器
- TypeORM - 查詢操作
- TypeORM - 事務
- TypeORM - 索引
- TypeORM - 實體偵聽器和日誌記錄
- 使用 JavaScript 的 TypeORM
- TypeORM - 在 MongoDB 中使用
- 使用 Express 的 TypeORM
- TypeORM - 遷移
- TypeORM - 使用 CLI
- TypeORM 有用資源
- TypeORM - 快速指南
- TypeORM - 有用資源
- TypeORM - 討論
TypeORM - 在 MongoDB 中使用
本章介紹 TypeORM 提供的廣泛的 MongoDB 資料庫支援。希望我們已經使用 npm 安裝了 mongodb。如果尚未安裝,請使用以下命令安裝 MongoDB 驅動程式,
npm install mongodb --save
建立專案
讓我們建立一個使用 MongoDB 的新專案,如下所示 −
typeorm init --name MyProject --database mongodb
配置 ormconfig.json
讓我們在 ormconfig.json 檔案中配置 MongoDB 主機、埠和資料庫選項,如下所示 −
ormconfig.json
{ "type": "mongodb", "host": "localhost", "port": 27017, "database": "test", "synchronize": true, "logging": false, "entities": [ "src/entity/**/*.ts" ], "migrations": [ "src/migration/**/*.ts" ], "subscribers": [ "src/subscriber/**/*.ts" ], "cli": { "entitiesDir": "src/entity", "migrationsDir": "src/migration", "subscribersDir": "src/subscriber" } }
定義實體和列
讓我們在 src 目錄中建立一個名為 Student 的新實體。實體和列是相同的。要生成主鍵列,我們使用 @PrimaryColumn 或
@PrimaryGeneratedColumn. 這可以定義為 @ObjectIdColumn。 簡單的示例如下所示 −
Student.ts
import {Entity, ObjectID, ObjectIdColumn, Column} from "typeorm"; @Entity() export class Student { @ObjectIdColumn() id: ObjectID; @Column() Name: string; @Column() Country: string; }
要儲存此實體,請開啟 index.ts 檔案並新增以下更改 −
index.ts
import "reflect-metadata"; import {createConnection} from "typeorm"; import {Student} from "./entity/Student"; createConnection().then(async connection => { console.log("Inserting a new Student into the database..."); const std = new Student(); std.Name = "Student1"; std.Country = "India"; await connection.manager.save(std); console.log("Saved a new user with id: " + std.id); console.log("Loading users from the database..."); const stds = await connection.manager.find(Student); console.log("Loaded users: ", stds); console.log("TypeORM with MongoDB"); }).catch(error => console.log(error));
現在,啟動伺服器,你將得到以下響應 −
npm start

MongoDB EntityManager
我們還可以使用 EntityManager 提取資料。簡單的示例如下所示 −
import {getManager} from "typeorm"; const manager = getManager(); const result = await manager.findOne(Student, { id:1 });
類似地,我們也可以使用儲存庫來訪問資料。
import {getMongoRepository} from "typeorm"; const studentRepository = getMongoRepository(Student); const result = await studentRepository.findOne({ id:1 });
如果你想使用相等選項過濾資料,如下所示 −
import {getMongoRepository} from "typeorm"; const studentRepository = getMongoRepository(Student); const result = await studentRepository.find({ where: { Name: {$eq: "Student1"}, } });
正如我們在本章中看到的,TypeORM 使得使用 MongoDB 資料庫引擎變得更加容易。
廣告