📅  最后修改于: 2020-10-19 03:44:45             🧑  作者: Mango
本章说明TypeORM提供的广泛的MongoDB数据库支持。希望我们已经使用npm安装了mongodb。如果尚未安装,请使用以下命令安装MongoDB驱动程序,
npm install mongodb --save
让我们使用MongoDB创建一个新项目,如下所示:
typeorm init --name MyProject --database mongodb
让我们在ormconfig.json文件中配置MongoDB主机,端口和数据库选项,如下所示-
{
"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。简单的例子如下所示-
import {Entity, ObjectID, ObjectIdColumn, Column} from "typeorm";
@Entity()
export class Student {
@ObjectIdColumn()
id: ObjectID;
@Column()
Name: string;
@Column()
Country: string;
}
要保存此实体,请打开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
我们还可以使用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数据库引擎的使用变得容易。