use*_*009 5 mongoose typescript
我正在尝试按照 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);
Run Code Online (Sandbox Code Playgroud)
他们还提供了一个扩展接口的替代示例Document
:
interface User extends Document {
name: string;
email: string;
avatar?: string;
}
Run Code Online (Sandbox Code Playgroud)
他们建议不要使用扩展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.
Run Code Online (Sandbox Code Playgroud)
我正在使用 Mongoose v 5.12.7。这件事有什么我不明白的地方吗?如何在不扩展文档的情况下创建架构?我想稍后测试它,并且我不想模拟 47 个或更多属性......
好吧,我想通了这个问题。我有两个问题。首先,我使用的是第三方@types/mongoose
包,现在不再需要它了,因为 Mongoose 本身支持 TypeScript。
然而,主要问题实际上是版本。尽管在文档中说自 v5.11.0 以来就存在新的支持,但我安装的 v5.12.7 和当前版本 \xe2\x80\x945.12.12 之间的差异实际上很重要。一旦我更新了版本,所有错误都消失了。
\n 归档时间: |
|
查看次数: |
3085 次 |
最近记录: |