TypeScript 支持
¥TypeScript Support
Mongoose 推出了 v5.11.0 中正式支持 TypeScript 绑定。Mongoose 的 index.d.ts
文件支持多种语法,并尽可能与 @types/mongoose
兼容。本指南描述了 Mongoose 在 TypeScript 中使用 Mongoose 的推荐方法。
¥Mongoose introduced officially supported TypeScript bindings in v5.11.0.
Mongoose's index.d.ts
file supports a wide variety of syntaxes and strives to be compatible with @types/mongoose
where possible.
This guide describes Mongoose's recommended approach to working with Mongoose in TypeScript.
创建你的第一个文档
¥Creating Your First Document
要开始在 TypeScript 中使用 Mongoose,你需要:
¥To get started with Mongoose in TypeScript, you need to:
创建一个代表 MongoDB 中文档的接口。
¥Create an interface representing a document in MongoDB.
创建一个 结构 对应的文档接口。
¥Create a Schema corresponding to the document interface.
创建一个模型。
¥Create a Model.
import { Schema, model, connect } from 'mongoose';
// 1. Create an interface representing a document in MongoDB.
interface IUser {
name: string;
email: string;
avatar?: string;
}
// 2. Create a Schema corresponding to the document interface.
const userSchema = new Schema<IUser>({
name: { type: String, required: true },
email: { type: String, required: true },
avatar: String
});
// 3. Create a Model.
const User = model<IUser>('User', userSchema);
run().catch(err => console.log(err));
async function run() {
// 4. Connect to MongoDB
await connect('mongodb://127.0.0.1:27017/test');
const user = new User({
name: 'Bill',
email: 'bill@initech.com',
avatar: 'https://i.imgur.com/dM7Thhn.png'
});
await user.save();
console.log(user.email); // 'bill@initech.com'
}
作为开发者,你有责任确保你的文档界面与你的 Mongoose 结构保持一致。例如,如果 email
在你的 Mongoose 结构中是 required
,但在你的文档界面中是可选的,Mongoose 不会报告错误。
¥You as the developer are responsible for ensuring that your document interface lines up with your Mongoose schema.
For example, Mongoose won't report an error if email
is required
in your Mongoose schema but optional in your document interface.
User()
构造函数返回 HydratedDocument<IUser>
的实例。IUser
是一个文档接口,它代表了 MongoDB 中 IUser
对象的原始对象结构。HydratedDocument<IUser>
代表一个水合 Mongoose 文档,包含方法、虚拟和其他 Mongoose 特定的功能。
¥The User()
constructor returns an instance of HydratedDocument<IUser>
.
IUser
is a document interface, it represents the raw object structure that IUser
objects look like in MongoDB.
HydratedDocument<IUser>
represents a hydrated Mongoose document, with methods, virtuals, and other Mongoose-specific features.
import { HydratedDocument } from 'mongoose';
const user: HydratedDocument<IUser> = new User({
name: 'Bill',
email: 'bill@initech.com',
avatar: 'https://i.imgur.com/dM7Thhn.png'
});
ObjectId 和其他 Mongoose 类型
¥ObjectIds and Other Mongoose Types
要定义 ObjectId
类型的属性,你应该在 TypeScript 文档接口中使用 Types.ObjectId
。你应该在结构定义中使用 'ObjectId'
或 Schema.Types.ObjectId
。
¥To define a property of type ObjectId
, you should use Types.ObjectId
in the TypeScript document interface. You should use 'ObjectId'
or Schema.Types.ObjectId
in your schema definition.
import { Schema, Types } from 'mongoose';
// 1. Create an interface representing a document in MongoDB.
interface IUser {
name: string;
email: string;
// Use `Types.ObjectId` in document interface...
organization: Types.ObjectId;
}
// 2. Create a Schema corresponding to the document interface.
const userSchema = new Schema<IUser>({
name: { type: String, required: true },
email: { type: String, required: true },
// And `Schema.Types.ObjectId` in the schema definition.
organization: { type: Schema.Types.ObjectId, ref: 'Organization' }
});
这是因为 Schema.Types.ObjectId
是 继承自 SchemaType 的类,而不是用于创建新 MongoDB ObjectId 的类。
¥That's because Schema.Types.ObjectId
is a class that inherits from SchemaType, not the class you use to create a new MongoDB ObjectId.
使用自定义绑定
¥Using Custom Bindings
如果 Mongoose 的内置 index.d.ts
文件不适合你,你可以在 package.json
的安装后脚本中将其删除,如下所示。不过,在此之前,请 在 Mongoose 的 GitHub 页面上打开一个问题 并描述你遇到的问题。
¥If Mongoose's built-in index.d.ts
file does not work for you, you can remove it in a postinstall script in your package.json
as shown below.
However, before you do, please open an issue on Mongoose's GitHub page and describe the issue you're experiencing.
{
"postinstall": "rm ./node_modules/mongoose/index.d.ts"
}
下一步
¥Next Up
现在你已经了解了如何在 TypeScript 中使用 Mongoose 的基础知识,让我们来看看 TypeScript 中的静态。
¥Now that you've seen the basics of how to use Mongoose in TypeScript, let's take a look at statics in TypeScript.