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.PRIMARYReadPreference.PRIMARY_PREFERREDReadPreference.SECONDARYReadPreference.SECONDARY_PREFERREDReadPreference.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
根据过滤条件更新集合中的单个文档。
MongoDB support
TypeORM has basic MongoDB support (Node.js driver v7 or later).
Most of TypeORM functionality is RDBMS-specific, this page contains all MongoDB-specific functionality.
Installation
npm install mongodbData Source Options
appName- The name of the application that created this MongoClient instance. MongoDB will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections.authMechanism- Sets the authentication mechanism that MongoDB will use to authenticate the connection.authSource- Specify the database name associated with the user's credentials.autoEncryption- Optionally enable in-use auto encryption.checkServerIdentity- Verifies the certificatecertis issued tohostname.compressors- An array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance.connectTimeoutMS- The time in milliseconds to attempt a connection before timing out. Default:30000.database- Database name.directConnection- Allow a driver to force a Single topology type with a connection string containing one host.driver- The driver object. Defaults torequire("mongodb").family- IP family.forceServerObjectId- Force server to assign _id values instead of driver. Default:false.host- Database host.hostReplicaSet- Database host replica set.ignoreUndefined- Specify if the BSON serializer should ignore undefined fields. Default:false.localThresholdMS- The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances.maxStalenessSeconds- Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. Minimum is 90 seconds.minPoolSize- The minimum number of connections in the connection pool.monitorCommands- Enable command monitoring for this client.noDelay- TCP Connection no delay.password- Database password.pkFactory- A primary key factory object for generation of custom _id keys.poolSize- Maximum number of connections in the connection pool. Mapped to the MongoDB driver'smaxPoolSizeoption.port- Database host port. Default mongodb port is27017.promoteBuffers- Promotes Binary BSON values to native Node Buffers. Default:false.promoteLongs- Promotes Long values to number if they fit inside the 53-bit resolution. Default:true.promoteValues- Promotes BSON values to native types where possible, set to false to only receive wrapper types. Default:true.proxyHost- Configures a Socks5 proxy host used for creating TCP connections.proxyPassword- Configures a Socks5 proxy password when the proxy requires username/password authentication.proxyPort- Configures a Socks5 proxy port used for creating TCP connections.proxyUsername- Configures a Socks5 proxy username when the proxy requires username/password authentication.raw- Return document results as raw BSON buffers. Default:false.readConcern- Specify a read concern for the collection.readPreference- The preferred read preference.ReadPreference.PRIMARYReadPreference.PRIMARY_PREFERREDReadPreference.SECONDARYReadPreference.SECONDARY_PREFERREDReadPreference.NEAREST
readPreferenceTags- Specifies the tags document as a comma-separated list of colon-separated key-value pairs.replicaSet- Specifies the name of the replica set, if the mongod is a member of a replica set.retryWrites- Enable retryable writes.serializeFunctions- Serialize functions on any object. Default:false.socketTimeoutMS- The time in milliseconds to attempt a send or receive on a socket before the attempt times out. Default:360000.tls- Enables or disables TLS/SSL for the connection. Default:false.tlsAllowInvalidCertificates- Bypasses validation of the certificates presented by the mongod/mongos instance. Default:false.tlsCAFile- Specifies the location of a local .pem file that contains the root certificate chain from the Certificate Authority.tlsCertificateKeyFile- Specifies the location of a local .pem file that contains the client's TLS/SSL certificate and key.tlsCertificateKeyFilePassword- Specifies the password to decrypt thetlsCertificateKeyFile.url- Connection url where the connection is performed. Please note that other data source options will override parameters set from url.username- Database username.writeConcern- A MongoDB WriteConcern, which describes the level of acknowledgement requested from MongoDB for write operations.
Additional options can be added to the extra object and will be passed directly to the client library. See more in mongodb's documentation for Connection Options.
Defining entities and columns
Defining entities and columns is almost the same as in relational databases, the main difference is that you must use @ObjectIdColumn instead of @PrimaryColumn or @PrimaryGeneratedColumn.
Simple entity example:
import { ObjectId } from "mongodb"
import { Entity, ObjectIdColumn, Column } from "typeorm"
@Entity()
export class User {
@ObjectIdColumn()
_id: ObjectId
@Column()
firstName: string
@Column()
lastName: string
}And this is how you bootstrap the app:
import { DataSource } from "typeorm"
const myDataSource = new DataSource({
type: "mongodb",
host: "localhost",
port: 27017,
database: "test",
})Defining subdocuments (embed documents)
Since MongoDB stores objects and objects inside objects (or documents inside documents), you can do the same in 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[]
}If you save this entity:
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)The following document will be saved in the database:
{
"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
}
]
}Selecting specific fields with select
You can project only the fields you need using the select option on find* methods. The object is translated into a MongoDB projection; nested embedded documents use object syntax and are flattened to dot-path projections.
const products = await myDataSource.getMongoRepository(Product).find({
select: { name: true, specs: { weight: true } },
})The example above returns each product with only name and specs.weight populated (plus the entity id). Unknown property names, whether at the top level or inside an embedded document, throw EntityPropertyNotFoundError — matching the behavior of SQL drivers.
Using MongoEntityManager and MongoRepository
You can use the majority of methods inside the EntityManager (except for RDBMS-specific, like query and transaction). For example:
const timber = await myDataSource.manager.findOneBy(User, {
firstName: "Timber",
lastName: "Saw",
})For MongoDB there is also a separate MongoEntityManager which extends EntityManager.
const timber = await myDataSource.manager.findOneBy(User, {
firstName: "Timber",
lastName: "Saw",
})Just like separate like MongoEntityManager there is a MongoRepository with extended Repository:
const timber = await myDataSource.getMongoRepository(User).findOneBy({
firstName: "Timber",
lastName: "Saw",
})Use Advanced options in 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" }],
},
})Querying subdocuments
const users = await myDataSource.getMongoRepository(User).find({
where: {
"profile.education": { $eq: "Tree School" },
},
})Querying Array of subdocuments
// Query users with photos of size less than 500
const users = await myDataSource.getMongoRepository(User).find({
where: {
"photos.size": { $lt: 500 },
},
})Both MongoEntityManager and MongoRepository contain a lot of useful MongoDB-specific methods:
createCursor
Create a cursor for a query that can be used to iterate over results from MongoDB.
createEntityCursor
Create a cursor for a query that can be used to iterate over results from MongoDB. This returns a modified version of the cursor that transforms each result into Entity models.
aggregate
Execute an aggregation framework pipeline against the collection.
bulkWrite
Perform a bulkWrite operation without a fluent API.
count
Count the number of matching documents in the db to a query.
countDocuments
Count the number of matching documents in the db to a query.
createCollectionIndex
Create an index on the db and collection.
createCollectionIndexes
Create multiple indexes in the collection. Index specifications are defined at createIndexes.
deleteMany
Delete multiple documents on MongoDB.
deleteOne
Delete a document on MongoDB.
distinct
The distinct command returns a list of distinct values for the given key across a collection.
dropCollectionIndex
Drops an index from this collection.
dropCollectionIndexes
Drops all indexes from the collection.
findOneAndDelete
Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation.
findOneAndReplace
Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation.
findOneAndUpdate
Find a document and update it in one atomic operation, requires a write lock for the duration of the operation.
geoHaystackSearch
Execute a geo search using a geo haystack index on a collection.
geoNear
Execute the geoNear command to search for items in the collection.
group
Run a group command across a collection.
collectionIndexes
Retrieve all the indexes of the collection.
collectionIndexExists
Retrieve if an index exists on the collection
collectionIndexInformation
Retrieve this collection's index info.
initializeOrderedBulkOp
Initiate an In order bulk write operation; operations will be serially executed in the order they are added, creating a new operation for each switch in types.
initializeUnorderedBulkOp
Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
insertMany
Insert an array of documents into MongoDB.
insertOne
Insert a single document into MongoDB.
isCapped
Return if the collection is a capped collection.
listCollectionIndexes
Get the list of all indexes information for the collection.
parallelCollectionScan
Return N number of parallel cursors for a collection allowing parallel reading of the entire collection. There are no ordering guarantees for returned results
reIndex
Reindex all indexes on the collection Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.
rename
Change the name of an existing collection.
replaceOne
Replace a document on MongoDB.
updateMany
Update multiple documents within the collection based on the filter.
updateOne
Update a single document within the collection based on the filter.