TypeORM – Working with MongoDB


TypeORM – Working with MongoDB



”;


This chapter explains the extensive MongoDB database support provided by TypeORM. Hopefully, we have installed mongodb using npm. If it is not installed, use the below command to install MongoDB driver,


npm install mongodb --save

Creating a project

Let’s create a new project using MongoDB as follows −


typeorm init --name MyProject --database mongodb

Configure ormconfig.json

Let’s configure MongoDB host, port and database options in ormconfig.json file as specified below −

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

Define entities and columns

Let us create a new entity named Student inside your src directory. Entities and columns are same. To generate primary key column, we use @PrimaryColumn or

@PrimaryGeneratedColumn. This can be defined as @ObjectIdColumn. Simple example is shown below −

Student.ts


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

@Entity() 
export class Student {  

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

To save this entity, open index.ts file and add the following changes −

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

Now, start your server and you will get the following response −


npm start


Start Server

MongoDB EntityManager

We can also use EntityManager to fetch data. Simple example is shown below −


import {getManager} from "typeorm";

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

Similarly, we can also use repository to access data.


import {getMongoRepository} from "typeorm"; 

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

If you want to filter the data using equal option as follows −


import {getMongoRepository} from "typeorm"; 

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

As we seen in this chapter, TypeORM makes it easy to work with MongoDB database engine.

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *