【问题标题】:Mongoose document type declarationMongoose 文档类型声明
【发布时间】:2021-04-28 03:03:49
【问题描述】:

我知道这可能太基本了,但我不记得如何正确地做到这一点。我想声明一个 Mongoose 文档以使用 VS Code IntelliSense 来检索数据。

现在,document 被声明为 any,因为 findById() 返回 any

const document = await MyModel.findById(docId);

所以,每当我想拨打document.updateOne() 之类的电话时,我都没有开启智能感知功能。

我尝试过使用类似的东西:

import { Model, Document } from 'mongoose';
...
const document: Model<Document> = await MyModel.findById(docId);

但这不让我能够直接引用内部属性,如 document.title 或任何其他属性。

那么,声明document 的正确方法是什么?

【问题讨论】:

    标签: mongodb typescript mongoose visual-studio-code intellisense


    【解决方案1】:

    您的 MyModel 具有某种文档类型,extends 猫鼬 Document 类型并添加可能会添加一些自己的属性。这就是您要使用的泛型。

    您在检索文档时不想设置泛型 (&lt;Document&gt;),而是希望在 MyModel 对象本身上设置泛型,以便打字稿为findById 和任何其他方法推断出正确的类型。所以你想在你创建MyModel的地方处理这个。

    interface MyDocument extends Document {
        title: string;
    }
    
    const MyModel = mongoose.model<MyDocument>(name, schema);
    

    现在document 被推断为在这里输入MyDocument | null

    const document = await MyModel.findById(docId);
    

    【讨论】:

    • 我这样做了,但document 仍然是any 类型
    • 嗯...不应该是这样,所以我不确定出了什么问题。您可以在 Typescript Playground 或 CodeSandbox 中发布可重现的示例吗?这就是我所看到的:tsplay.dev/oN9Rqm
    • 不确定出了什么问题......但在操场上确实有效:tsplay.dev/oN9Rqm
    • 好吧,无论如何它应该可以工作......所以谢谢......我认为这是一个 VS Code 问题或其他什么,我没有修改我的代码来重现它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 2013-03-13
    • 2015-11-06
    相关资源
    最近更新 更多