为什么这不会引发编译错误? (猫鼬,打字稿,MongoDB)

时间:2020-08-22 20:08:55

标签: mongodb typescript express mongoose

我目前正在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;

那么那个文档?:这就是为什么没有编译错误的原因。这是否意味着一般来说,当我们将Mongo模式与TS接口结合在一起时,我们只能对读取,更新和删除进行类型检查,而不能对创建进行检查?

1 个答案:

答案 0 :(得分:0)

您对void isort(void* ptr, size_t count, size_t size, int (*comp)(const void*, const void*)) { size_t i; size_t j; bool sorted; void* a; void* b; void* t; // don't allocate temporary memory when unneeded if (count == 0) return; t = malloc(size); for (i = 0; i < count; ++i) { sorted = false; for (j = i - 1; j >= 0 && !sorted; --j) { sorted = true; a = (char*)ptr + size * j; b = (char*)ptr + size * (j + 1); if (comp(a, b) > 0) { memcpy(t, a, size); memcpy(a, b, size); memcpy(b, t, size); sorted = false; } } } free(t); } 的看法是正确的,我们无法对create方法进行类型检查。当您尝试将其保存到数据库中时(仅由于架构检查),它将引发错误。