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