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 数据库引擎配合使用。