【问题标题】:Why does this not raise a compilation error? (Mongoose, Typescript, MongoDB)为什么这不会引发编译错误? (猫鼬,打字稿,MongoDB)
【发布时间】:2020-12-11 21:22:44
【问题描述】:

我目前正在 Typescript 中设置一个 MERN 项目,我想知道为什么以下内容不会在 TS 中产生编译错误。

这是我的模型:

import { Document, Schema, model } from "mongoose";
export interface Hello extends Document {
  name: string;
}

const helloSchema = new Schema({
  name: {
    required: true,
    type: String,
  },
});

const helloModel = model<Hello>("Hello", helloSchema);

export default helloModel;

然后这样使用:

import express from "express";
import helloModel from "./model";

const app = express();

app.get("/", (req, res) => {
  res.send("hi");
});

const x = new helloModel({ age: 1 }); <===== no errors here

app.listen(7000);

我希望会有编译错误说 x 不符合接口。我是否错误地使用了模型?如果不是很清楚(我希望不是),我对 MongoDB 和 Typescript 还很陌生。

非常感谢任何可以解释的人。

编辑跟进 我在@types 文件中找到了这个:

/**
     * Model constructor
     * Provides the interface to MongoDB collections as well as creates document instances.
     * @param doc values with which to create the document
     * @event error If listening to this event, it is emitted when a document
     *   was saved without passing a callback and an error occurred. If not
     *   listening, the event bubbles to the connection used to create this Model.
     * @event index Emitted after Model#ensureIndexes completes. If an error
     *   occurred it is passed with the event.
     * @event index-single-start Emitted when an individual index starts within
     *   Model#ensureIndexes. The fields and options being used to build the index
     *   are also passed with the event.
     * @event index-single-done Emitted when an individual index finishes within
     *   Model#ensureIndexes. If an error occurred it is passed with the event.
     *   The fields, options, and index name are also passed.
     */
    new (doc?: any): T;

那么那个 doc?: any 就是为什么没有编译错误。这是否意味着通常当我们将 Mongo 模式与我们的 TS 接口连接时,我们只能在读取、更新和删除而不是在创建时进行类型检查?

【问题讨论】:

  • 我认为您假设驱动程序具有严格的输入信息,我将验证这个假设是否准确。
  • 嗨@D.SM,谢谢你 - 你能进一步解释一下吗?对不起,我无知。浏览了 .d.ts 文件并尝试弄乱它;很清楚该文档?:这里有任何必要,我只是想弄清楚为什么会这样
  • 我对这种情况的印象是驱动程序是用 js 编写的(现在正在用 ts 重写),并且键入注释是社区维护的。因此,注释不一定在可以被指定的任何地方都指定类型。
  • 谢谢@D.SM。那是有道理的。有趣的是,在输入文件中,我尝试将 new(doc?: any): T 切换为 new(doc?: T):T (其中 T 扩展了 mongoose.Document,然后当我尝试实例化 TS 编译器想要的新文档时Document 接口的所有相关部分以及我的接口作为参数(这是有道理的)。我只是觉得有趣的是 create() 只是意味着 new().save()...跨度>

标签: mongodb typescript express mongoose


【解决方案1】:

doc?: any 说得对,我们不能对 create 方法进行类型检查。当您尝试将其保存到数据库时,它会抛出错误,并且只是因为模式检查。

【讨论】:

  • 谢谢你,但恐怕我还是不明白。为什么 create 方法不能进行类型检查?
  • @Doomel 还有 is 对 create() 方法进行类型检查,但不仅仅是在实例化新文档时。
猜你喜欢
  • 2017-02-14
  • 2021-11-14
  • 2016-06-14
  • 2021-03-13
  • 2016-05-24
  • 2020-06-21
  • 2016-02-05
  • 2020-05-11
  • 2020-01-30
相关资源
最近更新 更多