创建新文档的函数的结果类型 - 猫鼬模式和模型

问题描述 投票:0回答:1

在我们的打字稿项目中,有一个

myDocument.model.ts
,其内容为:

import * as mongoose from 'mongoose';

const DocumentSchema = new mongoose.Schema({
  url: String,
  date: Date,
});

export default mongoose.model("Document", DocumentSchema);

repository.ts
中有一个功能:

import Document from "./myDocument.model";
    
function addDocument(url:string):Document {
 let newDoc = new Document();
 newDoc.url = url;
 newDoc.date = new Date();
 newDoc.save();
 return newDoc;
}

我想指定这个

addDocument(..)
函数的返回类型 - 但不能。我将上面的导出解释为
Document
是一个像类一样的
type
,可以实例化 - 并且
newDoc
实例至少有两个字段(url、日期),还有几个附加字段,如
_id
 id
,一些实例和静态方法,例如由 mongoose.model(...) 调用生成的
save()
。所以函数返回类型应该是
Document
:

public addDocument(url:string): Document {
  ...
  return newDoc;
}

但是在这种情况下 TS 编译器会说

错误 TS2740:输入“文档 & { url?:字符串;日期?: 日期; } & { _id: 对象 ID; }' 缺少“文档”类型中的以下属性:URL、alinkColor、全部、锚点以及其他 250 个属性。

我错过了什么?

typescript mongodb mongoose mongoose-schema
1个回答
0
投票

你犯了两个错误,即-

  1. 当您使用
    Document
    添加函数返回类型的签名时,您无意中错误地在浏览器中引用了 DOM 中的 Document。尝试将鼠标悬停在文档上,您将看到说明。
  2. 如果您希望使用
    Document
    模型的实例来输入它,则需要使用
    IntanceType
    实用程序,参数为
    typeof Document
import mongoose from "mongoose";

const DocumentSchema = new mongoose.Schema({
    url: String,
    date: Date,
});

const Document = mongoose.model("Document", DocumentSchema);

// Wrong, here you're using the DOM interface called Document
function addDocumentWrong(url: string): Document { 
    let newDoc = new Document();
    newDoc.url = url;
    newDoc.date = new Date();
    newDoc.save();
    return newDoc;
}

// Correct, here the an instance type of `typeof Document` model as the return type.
function addDocument(url: string): InstanceType<typeof Document> { // Correct
    let newDoc = new Document();
    newDoc.url = url;
    newDoc.date = new Date();
    newDoc.save();
    return newDoc;
}

游乐场链接

© www.soinside.com 2019 - 2024. All rights reserved.