【发布时间】:2021-08-20 01:51:54
【问题描述】:
我正在尝试按照 Mongoose 文档中给出的说明来支持 TypeScript:https://mongoosejs.com/docs/typescript.html。
在文档中,他们提供了以下示例:
import { Schema, model, connect } from 'mongoose';
// 1. Create an interface representing a document in MongoDB.
interface User {
name: string;
email: string;
avatar?: string;
}
// 2. Create a Schema corresponding to the document interface.
const schema = new Schema<User>({
name: { type: String, required: true },
email: { type: String, required: true },
avatar: String
});
// 3. Create a Model.
const UserModel = model<User>('User', schema);
他们还提供了接口扩展 Document 的替代示例:
interface User extends Document {
name: string;
email: string;
avatar?: string;
}
他们建议不要使用扩展Document 的方法。但是,当我尝试他们的确切代码(没有extends)时,我收到以下错误:
Type 'User' does not satisfy the constraint 'Document<any, {}>'.
Type 'User' is missing the following properties from type 'Document<any, {}>': $getAllSubdocs, $ignore, $isDefault, $isDeleted, and 47 more.
我正在使用 Mongoose v 5.12.7。有什么我不明白的吗?如何在不扩展文档的情况下创建架构?我想稍后对其进行测试,并且我不想模拟 47 个或更多属性...
【问题讨论】:
标签: typescript mongoose