MongoDB
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
MongoDB 支持
TypeORM 提供基础的 MongoDB 支持。 由于 TypeORM 大部分功能是专为关系型数据库设计的, 本文档仅包含 MongoDB 特有功能的说明。
安装
npm install mongodb
数据源选项
-
url- 执行连接操作的 URL。请注意,其他数据源选项会覆盖 URL 中设置的参数。 -
host- 数据库主机地址。 -
port- 数据库主机端口。MongoDB 默认端口为27017。 -
username- 数据库用户名(替代auth.user)。 -
password- 数据库密码(替代auth.password)。 -
database- 数据库名称。 -
poolSize- 设置每个服务器或代理连接的最大连接池大小。 -
tls- 使用 TLS/SSL 连接(需要 MongoDB 2.4+ 且支持 SSL)。默认值:false。 -
tlsAllowInvalidCertificates- 当服务器 TLS 证书无效时是否生成错误。默认值:false。 -
tlsCAFile- 指定包含证书颁发机构根证书链的本地 .pem 文件路径。 -
tlsCertificateKeyFile- 指定包含客户端 TLS/SSL 证书和密钥的本地 .pem 文件路径。 -
tlsCertificateKeyFilePassword- 指定解密tlsCertificateKeyFile的密码。 -
keepAlive- TCP 套接字上启动 keepAlive 前的等待毫秒数。默认值:30000。 -
connectTimeoutMS- TCP 连接超时设置。默认值:30000。 -
socketTimeoutMS- TCP 套接字超时设置。默认值:360000。 -
replicaSet- 要连接的副本集名称。 -
authSource- 当数据库认证依赖于其他数据库时指定认证源。 -
writeConcern- 写关注设置。 -
forceServerObjectId- 强制服务器分配 _id 值而非驱动程序分配。默认值:false。 -
serializeFunctions- 是否序列化任意对象中的函数。默认值:false。 -
ignoreUndefined- 指定 BSON 序列化器是否忽略 undefined 字段。默认值:false。 -
raw- 是否将文档结果作为原始 BSON 缓冲区返回。默认值:false。 -
promoteLongs- 当 Long 值在 53 位精度范围内时是否提升为 number 类型。默认值:true。 -
promoteBuffers- 是否将 Binary BSON 值提升为 Node.js 原生 Buffer。默认值:false。 -
promoteValues- 是否尽可能将 BSON 值提升为原生类型(设为 false 则只返回包装类型)。 默认值:true。 -
readPreference- 优先使用的读偏好设置:ReadPreference.PRIMARYReadPreference.PRIMARY_PREFERREDReadPreference.SECONDARYReadPreference.SECONDARY_PREFERREDReadPreference.NEAREST
-
pkFactory- 用于生成自定义 _id 的主键工厂对象。 -
readConcern- 指定集合的读关注(仅支持 MongoDB 3.2+)。 -
maxStalenessSeconds- 为次要节点读取指定最大陈旧秒数(最小值 90 秒)。 -
appName- 创建此 MongoClient 实例的应用程序名称(MongoDB 3.4+ 会在建立连接时将该值记录到服务器日志,同时也会记录到慢查询日志和性能分析集合)。 -
authMechanism- 设置 MongoDB 用于连接认证的认证机制。 -
directConnection- 指定是否将所有操作强制分发到指定主机。
可通过 extra 对象添加额外选项,这些选项将直接传递给客户端库。更多信息请参阅 mongodb 文档中的 连接选项。
定义实体与列
定义实体和列的方式与关系型数据库几乎相同,主要区别在于必须使用 @ObjectIdColumn 替代 @PrimaryColumn 或 @PrimaryGeneratedColumn。
简单实体示例:
import { Entity, ObjectId, 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 { Entity, ObjectId, ObjectIdColumn, Column } from "typeorm"
export class Profile {
@Column()
about: string
@Column()
education: string
@Column()
career: string
}
import { Entity, ObjectId, 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[]
}
保存此实体后:
import { getMongoManager } from "typeorm"
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),
]
const manager = getMongoManager()
await 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
}
]
}
使用 MongoEntityManager 与 MongoRepository
除特定于关系型数据库的方法(如 query 和 transaction)外,您可使用 EntityManager 中的大多数方法,例如:
const timber = await myDataSource.manager.findOneBy(User, {
firstName: "Timber",
lastName: "Saw",
})
针对 MongoDB 还提供了扩展自 EntityManager 的独立 MongoEntityManager。
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() 中使用高级选项:
等于:
const timber = await myDataSource.getMongoRepository(User).find({
where: {
firstName: { $eq: "Timber" },
},
})
小于:
const timber = await myDataSource.getMongoRepository(User).find({
where: {
age: { $lt: 60 },
},
})
包含:
const timber = await myDataSource.getMongoRepository(User).find({
where: {
firstName: { $in: ["Timber", "Zhang"] },
},
})
排除:
const timber = await myDataSource.getMongoRepository(User).find({
where: {
firstName: { $not: { $in: ["Timber", "Zhang"] } },
},
})
或:
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" },
},
})
查询子文档数组
// Query users with photos of size less than 500
const users = await myDataSource.getMongoRepository(User).find({
where: {
"photos.size": { $lt: 500 },
},
})
MongoEntityManager 和 MongoRepository 均包含大量 MongoDB 专属实用方法:
createCursor
为查询创建游标,用于遍历 MongoDB 返回的结果集。
createEntityCursor
为查询创建游标(返回经过修改的版本),将每个结果转换为实体模型。
aggregate
对集合执行聚合管道操作。
bulkWrite
执行批量写入操作(非流式 API)。
count
统计数据库中匹配查询条件的文档数量。
countDocuments
统计数据库中匹配查询条件的文档数量。
createCollectionIndex
在数据库集合上创建索引。
createCollectionIndexes
在集合中创建多个索引(仅支持 MongoDB 2.6+,低版本会抛出"command not supported"错误)。索引规范定义参见 createIndexes。
deleteMany
删除 MongoDB 中的多个文档。
deleteOne
删除 MongoDB 中的单个文档。
distinct
distinct 命令返回集合中指定键的所有不重复值列表。
dropCollectionIndex
从当前集合中删除指定索引。
dropCollectionIndexes
删除集合中的所有索引。
findOneAndDelete
以原子操作方式查找并删除文档,该操作期间需 要持有写入锁。
findOneAndReplace
以原子操作方式查找并替换文档,该操作期间需要持有写入锁。
findOneAndUpdate
以原子操作方式查找并更新文档,该操作期间需要持有写入锁。
geoHaystackSearch
使用集合的地理草堆索引执行地理空间搜索。
geoNear
执行 geoNear 命令在集合中搜索项目。
group
对整个集合执行分组命令。
collectionIndexes
获取集合的所有索引信息。
collectionIndexExists
检查集合上是否存在指定索引。
collectionIndexInformation
获取当前集合的索引信息。
initializeOrderedBulkOp
初始化有序批量写入操作:操作将按添加顺序串行执行,每种操作类型变化时会创建新操作。
initializeUnorderedBulkOp
初始化无序批量写入操作:所有操作将被缓冲为插入/更新/删除命令,以乱序方式执行。
insertMany
向 MongoDB 中插入多个文档组成的数组。
insertOne
向 MongoDB 中插入单个文档。
isCapped
判断当前集合是否为固定大小集合(capped collection)。
listCollectionIndexes
获取集合所有索引的详细信息列表。
parallelCollectionScan
返回多个并行游标以支持全集合并行读取,返回结果不保证顺序。
reIndex
重建集合所有索引(警告:reIndex 是阻塞操作,索引将在前台重建,大集合操作缓慢)。
rename
重命名现有集合。
replaceOne
替换 MongoDB 中的单个文档。
stats
获取集合的所有统计信息。
updateMany
根据筛选条件更新集合中的多个文档。
updateOne
根据筛选条件更新集合中的单个文档。