TypeORM - Lavorare con MongoDB

Questo capitolo spiega l'ampio supporto del database MongoDB fornito da TypeORM. Si spera di aver installato mongodb utilizzando npm. Se non è installato, utilizzare il comando seguente per installare il driver MongoDB,

npm install mongodb --save

Creare un progetto

Creiamo un nuovo progetto usando MongoDB come segue:

typeorm init --name MyProject --database mongodb

Configura ormconfig.json

Configuriamo le opzioni dell'host, della porta e del database di MongoDB nel file ormconfig.json come specificato di seguito -

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" 
   } 
}

Definisci entità e colonne

Creiamo una nuova entità chiamata Student all'interno della tua directory src. Le entità e le colonne sono le stesse. Per generare la colonna della chiave primaria, usiamo@PrimaryColumn o

@PrimaryGeneratedColumn. Questo può essere definito come @ObjectIdColumn. Di seguito è mostrato un semplice esempio:

Student.ts

import {Entity, ObjectID, ObjectIdColumn, Column} from "typeorm"; 

@Entity() 
export class Student {  

   @ObjectIdColumn() 
   id: ObjectID; 
   
   @Column() 
   Name: string; 
   
   @Column() 
   Country: string; 
}

Per salvare questa entità, apri il file index.ts e aggiungi le seguenti modifiche:

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

Ora avvia il tuo server e otterrai la seguente risposta:

npm start

MongoDB EntityManager

Possiamo anche usare EntityManager per recuperare i dati. Di seguito è mostrato un semplice esempio:

import {getManager} from "typeorm";

const manager = getManager(); 
const result = await manager.findOne(Student, { id:1 });

Allo stesso modo, possiamo anche utilizzare il repository per accedere ai dati.

import {getMongoRepository} from "typeorm"; 

const studentRepository = getMongoRepository(Student); 
const result = await studentRepository.findOne({ id:1 });

Se si desidera filtrare i dati utilizzando l'opzione uguale come segue:

import {getMongoRepository} from "typeorm"; 

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

Come abbiamo visto in questo capitolo, TypeORM rende facile lavorare con il motore di database MongoDB.