TypeORM中文文档 v1.1
数据库驱动 / MongoDB
GitHub

MongoDB

MongoDB 支持

TypeORM 提供了基础的 MongoDB 支持(Node.js 驱动 v7 或更高版本)。

TypeORM 的大部分功能都是 RDBMS 专属的,本页包含所有 MongoDB 专属功能。

安装

npm install mongodb

数据源选项

  • appName - 创建该 MongoClient 实例的应用名称。MongoDB 会在每次建立连接时把这个值打印到服务器日志中。它也会被记录在慢查询日志和 profile 集合中。

  • authMechanism - 设置 MongoDB 用于认证该连接的认证机制。

  • authSource - 指定与用户凭据关联的数据库名。

  • checkServerIdentity - 验证证书 cert 是否签发给 hostname。

  • autoEncryption - 可选地启用使用中自动加密。

  • compressors - 压缩器数组或逗号分隔的字符串,用于为该客户端与 mongod/mongos 实例之间的通信启用网络压缩。

  • connectTimeoutMS - 尝试连接多久(毫秒)后超时。默认:30000。

  • database - 数据库名。

  • directConnection - 允许驱动在连接字符串只含一个主机时强制使用 Single 拓扑类型。

  • driver - 驱动对象。默认是 require("mongodb")。

  • family - IP 协议族。

  • forceServerObjectId - 强制由服务器而不是驱动来分配 _id 值。默认:false。

  • host - 数据库主机。

  • hostReplicaSet - 数据库主机副本集。

  • ignoreUndefined - 指定 BSON 序列化器是否应忽略 undefined 字段。默认:false。

  • localThresholdMS - 在多个合适的 MongoDB 实例之间做选择时延迟窗口的大小(毫秒)。

  • maxStalenessSeconds - 指定从节点可以落后多少秒,之后客户端就不再用它执行读操作。最小为 90 秒。

  • minPoolSize - 连接池中的最小连接数。

  • monitorCommands - 为该客户端启用命令监控。

  • noDelay - TCP 连接无延迟。

  • password - 数据库密码。

  • pkFactory - 用于生成自定义 _id 键的主键工厂对象。

  • poolSize - 连接池中的最大连接数。映射到 MongoDB 驱动的 maxPoolSize 选项。

  • port - 数据库主机端口。mongodb 默认端口是 27017。

  • promoteBuffers - 把二进制 BSON 值提升为原生 Node Buffer。默认:false。

  • promoteLongs - 如果 Long 值能放进 53 位精度,就把它提升为 number。默认:true。

  • promoteValues - 尽可能把 BSON 值提升为原生类型,设为 false 则只接收包装类型。默认:true。

  • proxyHost - 配置用于创建 TCP 连接的 Socks5 代理主机。

  • proxyPassword - 当代理要求用户名/密码认证时,配置 Socks5 代理密码。

  • proxyPort - 配置用于创建 TCP 连接的 Socks5 代理端口。

  • proxyUsername - 当代理要求用户名/密码认证时,配置 Socks5 代理用户名。

  • raw - 把文档结果作为原始 BSON 缓冲区返回。默认:false。

  • readConcern - 为集合指定读关注(read concern)。

  • readPreference - 首选的读偏好。

    • ReadPreference.PRIMARY
    • ReadPreference.PRIMARY_PREFERRED
    • ReadPreference.SECONDARY
    • ReadPreference.SECONDARY_PREFERRED
    • ReadPreference.NEAREST
  • readPreferenceTags - 以逗号分隔的、冒号分隔的键值对列表形式指定 tags 文档。

  • replicaSet - 如果 mongod 是副本集成员,指定副本集的名称。

  • retryWrites - 启用可重试写入。

  • serializeFunctions - 序列化任何对象上的函数。默认:false。

  • socketTimeoutMS - 在 socket 上尝试发送或接收多久(毫秒)后超时。默认:360000。

  • tls - 为连接启用或禁用 TLS/SSL。默认:false。

  • tlsAllowInvalidCertificates - 跳过对 mongod/mongos 实例所提供证书的校验。默认:false。

  • tlsCAFile - 指定包含证书颁发机构根证书链的本地 .pem 文件位置。

  • tlsCertificateKeyFile - 指定包含客户端 TLS/SSL 证书和密钥的本地 .pem 文件位置。

  • tlsCertificateKeyFilePassword - 指定用于解密 tlsCertificateKeyFile 的密码。

  • url - 建立连接的连接 url。请注意,其他数据源选项会覆盖从 url 中设置的参数。

  • username - 数据库用户名。

  • writeConcern - 一个 MongoDB WriteConcern,描述对写操作向 MongoDB 请求的确认级别。

更多选项可以加到 extra 对象中,它们会被直接传给客户端库。更多内容见 mongodb 关于连接选项的文档。

定义实体与列

定义实体和列与关系型数据库中几乎相同,主要区别是你必须使用 @ObjectIdColumn 而不是 @PrimaryColumn 或 @PrimaryGeneratedColumn。

简单实体示例:

import { ObjectId } from "mongodb"
import { Entity, ObjectIdColumn, Column } from "typeorm"

@Entity()
export class User {
    @ObjectIdColumn()
    _id: ObjectId

    @Column()
    firstName: string

    @Column()
    lastName: string
}

这是启动应用的方式:

import { DataSource } from "typeorm"

const myDataSource = new DataSource({
    type: "mongodb",
    host: "localhost",
    port: 27017,
    database: "test",
})

定义子文档(嵌入文档)

由于 MongoDB 存储对象以及对象中的对象(或者说文档中的文档),你在 TypeORM 中也可以这样做:

import { ObjectId } from "mongodb"
import { Entity, ObjectIdColumn, Column } from "typeorm"

export class Profile {
    @Column()
    about: string

    @Column()
    education: string

    @Column()
    career: string
}
import { ObjectId } from "mongodb"
import { Entity, ObjectIdColumn, Column } from "typeorm"

export class Photo {
    @Column()
    url: string

    @Column()
    description: string

    @Column()
    size: number

    constructor(url: string, description: string, size: number) {
        this.url = url
        this.description = description
        this.size = size
    }
}
import { Entity, ObjectId, ObjectIdColumn, Column } from "typeorm"

@Entity()
export class User {
    @ObjectIdColumn()
    id: ObjectId

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column((type) => Profile)
    profile: Profile

    @Column((type) => Photo)
    photos: Photo[]
}

如果你保存这个实体:

const user = new User()
user.firstName = "Timber"
user.lastName = "Saw"
user.profile = new Profile()
user.profile.about = "About Trees and Me"
user.profile.education = "Tree School"
user.profile.career = "Lumberjack"
user.photos = [
    new Photo("me-and-trees.jpg", "Me and Trees", 100),
    new Photo("me-and-chakram.jpg", "Me and Chakram", 200),
]

await myDataSource.manager.save(user)

数据库中会保存如下文档:

{
    "firstName": "Timber",
    "lastName": "Saw",
    "profile": {
        "about": "About Trees and Me",
        "education": "Tree School",
        "career": "Lumberjack"
    },
    "photos": [
        {
            "url": "me-and-trees.jpg",
            "description": "Me and Trees",
            "size": 100
        },
        {
            "url": "me-and-chakram.jpg",
            "description": "Me and Chakram",
            "size": 200
        }
    ]
}

用 select 选取特定字段

你可以在 find* 方法上用 select 选项只投影出你需要的字段。该对象会被转换成 MongoDB 的投影;嵌套的嵌入文档使用对象语法,并被扁平化为点路径投影。

const products = await myDataSource.getMongoRepository(Product).find({
    select: { name: true, specs: { weight: true } },
})

上面的示例返回的每个 product 只填充 name 和 specs.weight(外加实体 id)。未知的属性名——无论在顶层还是在嵌入文档内部——都会抛出 EntityPropertyNotFoundError,这与 SQL 驱动的行为一致。

使用 MongoEntityManager 与 MongoRepository

你可以使用 EntityManager 中的大部分方法(RDBMS 专属的除外,比如 query 和 transaction)。例如:

const timber = await myDataSource.manager.findOneBy(User, {
    firstName: "Timber",
    lastName: "Saw",
})

对 MongoDB 还有一个单独的 MongoEntityManager,它继承自 EntityManager。

const timber = await myDataSource.manager.findOneBy(User, {
    firstName: "Timber",
    lastName: "Saw",
})

就像有单独的 MongoEntityManager 一样,也有一个扩展了 Repository 的 MongoRepository:

const timber = await myDataSource.getMongoRepository(User).findOneBy({
    firstName: "Timber",
    lastName: "Saw",
})

在 find() 中使用进阶选项:

Equal:

const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        firstName: { $eq: "Timber" },
    },
})

LessThan:

const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        age: { $lt: 60 },
    },
})

In:

const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        firstName: { $in: ["Timber", "Zhang"] },
    },
})

Not in:

const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        firstName: { $not: { $in: ["Timber", "Zhang"] } },
    },
})

Or:

const timber = await myDataSource.getMongoRepository(User).find({
    where: {
        $or: [{ firstName: "Timber" }, { firstName: "Zhang" }],
    },
})

查询子文档

const users = await myDataSource.getMongoRepository(User).find({
    where: {
        "profile.education": { $eq: "Tree School" },
    },
})

查询子文档数组

// 查询照片大小小于 500 的用户
const users = await myDataSource.getMongoRepository(User).find({
    where: {
        "photos.size": { $lt: 500 },
    },
})

MongoEntityManager 和 MongoRepository 都包含大量有用的 MongoDB 专属方法:

createCursor

为查询创建一个游标,可用于遍历来自 MongoDB 的结果。

createEntityCursor

为查询创建一个游标,可用于遍历来自 MongoDB 的结果。它返回游标的一个修改版本,会把每个结果转换成实体模型。

aggregate

针对集合执行聚合框架管道。

bulkWrite

不使用流式 API 执行 bulkWrite 操作。

count

统计数据库中匹配某查询的文档数量。

countDocuments

统计数据库中匹配某查询的文档数量。

createCollectionIndex

在数据库和集合上创建一个索引。

createCollectionIndexes

在集合中创建多个索引。索引规范定义见 createIndexes。

deleteMany

在 MongoDB 上删除多个文档。

deleteOne

在 MongoDB 上删除一个文档。

distinct

distinct 命令返回给定键在某个集合中的不同值列表。

dropCollectionIndex

从该集合中删除一个索引。

dropCollectionIndexes

从集合中删除所有索引。

findOneAndDelete

在一个原子操作中查找并删除文档,操作期间需要写锁。

findOneAndReplace

在一个原子操作中查找并替换文档,操作期间需要写锁。

findOneAndUpdate

在一个原子操作中查找并更新文档,操作期间需要写锁。

geoHaystackSearch

使用集合上的 geo haystack 索引执行地理搜索。

geoNear

执行 geoNear 命令,在集合中搜索条目。

group

跨集合运行 group 命令。

collectionIndexes

取回集合的所有索引。

collectionIndexExists

取回集合上是否存在某个索引

collectionIndexInformation

取回该集合的索引信息。

initializeOrderedBulkOp

发起一个有序批量写操作;各操作会按添加顺序串行执行,每遇到类型切换就创建一个新操作。

initializeUnorderedBulkOp

发起一个无序批量写操作。所有操作会被缓冲成 insert/update/remove 命令并乱序执行。

insertMany

向 MongoDB 插入一个文档数组。

insertOne

向 MongoDB 插入单个文档。

isCapped

返回该集合是否为固定大小(capped)集合。

listCollectionIndexes

获取该集合所有索引信息的列表。

parallelCollectionScan

为集合返回 N 个并行游标,允许并行读取整个集合。返回结果不保证顺序

reIndex

重建集合上的所有索引 警告:reIndex 是阻塞操作(索引在前台重建),对大集合会很慢。

rename

修改已有集合的名称。

replaceOne

在 MongoDB 上替换一个文档。

updateMany

根据过滤条件更新集合中的多个文档。

updateOne

根据过滤条件更新集合中的单个文档。