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 });

次のようにequalオプションを使用してデータをフィルタリングする場合-

import {getMongoRepository} from "typeorm"; 

const studentRepository = getMongoRepository(Student); 
const result = await studentRepository.find({ 
   where: { 
      Name: {$eq: "Student1"}, 
   } 
});

この章で見たように、TypeORMを使用するとMongoDBデータベースエンジンを簡単に操作できます。