在 TypeScript 中处理子文档
在 TypeScript 中,子文档很棘手。默认情况下,Mongoose 将文档接口中的对象属性视为嵌套属性,而不是子文档。
// 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()
返回的类型。
// 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!
子文档数组
您还可以使用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!