在 TypeScript 中处理子文档
¥Handling Subdocuments in TypeScript
TypeScript 中的子文档很棘手。默认情况下,Mongoose 将文档接口中的对象属性视为嵌套属性而不是子文档。
¥Subdocuments are tricky in TypeScript. By default, Mongoose treats object properties in document interfaces as nested properties rather than subdocuments.
// Setup
import { Schema, Types, model, Model } from 'mongoose';
// Subdocument definition
interface Names {
_id: Types.ObjectId;
firstName: string;
}
// Document definition
interface User {
names: Names;
}
// Models and schemas
type UserModelType = Model<User>;
const userSchema = new Schema<User, UserModelType>({
names: new Schema<Names>({ firstName: String })
});
const UserModel = model<User, UserModelType>('User', userSchema);
// Create a new document:
const doc = new UserModel({ names: { _id: '0'.repeat(24), firstName: 'foo' } });
// "Property 'ownerDocument' does not exist on type 'Names'."
// Means that `doc.names` is not a subdocument!
doc.names.ownerDocument();
Mongoose 提供了一种覆盖水合文档中类型的机制。定义一个单独的 THydratedDocumentType
并将其作为第 5 个通用参数传递给 mongoose.Model<>
。THydratedDocumentType
控制 Mongoose 对 "水合文档" 使用的类型,即 await UserModel.findOne()
、UserModel.hydrate()
和 new UserModel()
返回的类型。
¥Mongoose provides a mechanism to override types in the hydrated document.
Define a separate THydratedDocumentType
and pass it as the 5th generic param to mongoose.Model<>
.
THydratedDocumentType
controls what type Mongoose uses for "hydrated documents", that is, what await UserModel.findOne()
, UserModel.hydrate()
, and new UserModel()
return.
// Define property overrides for hydrated documents
type THydratedUserDocument = {
names?: mongoose.Types.Subdocument<Names>
}
type UserModelType = mongoose.Model<User, {}, {}, {}, THydratedUserDocument>;
const userSchema = new mongoose.Schema<User, UserModelType>({
names: new mongoose.Schema<Names>({ firstName: String })
});
const UserModel = mongoose.model<User, UserModelType>('User', userSchema);
const doc = new UserModel({ names: { _id: '0'.repeat(24), firstName: 'foo' } });
doc.names!.ownerDocument(); // Works, `names` is a subdocument!
子文档数组
¥Subdocument Arrays
你还可以使用 TMethodsAndOverrides
覆盖数组以正确键入子文档数组:
¥You can also override arrays to properly type subdocument arrays using TMethodsAndOverrides
:
// Subdocument definition
interface Names {
_id: Types.ObjectId;
firstName: string;
}
// Document definition
interface User {
names: Names[];
}
// TMethodsAndOverrides
type THydratedUserDocument = {
names?: Types.DocumentArray<Names>
}
type UserModelType = Model<User, {}, {}, {}, THydratedUserDocument>;
// Create model
const UserModel = model<User, UserModelType>('User', new Schema<User, UserModelType>({
names: [new Schema<Names>({ firstName: String })]
}));
const doc = new UserModel({});
doc.names[0].ownerDocument(); // Works!