簡體   English   中英

貓鼬打字稿?

[英]Mongoose with typescript?

我在 nodejs 和 typescript 中有一個項目。 我正在使用 mongoose 連接到 mongoDb 數據庫。 我的代碼看起來像這樣

import { Schema, Document, Model } from 'mongoose';
import * as mongoose from 'mongoose';

export interface IProblem extends Document {
  problem: string;
  solution: string;
}

const ProblemSchema = new Schema({
  problem: { type: String, required: true },
  solution: { type: String, required: true },
});

export async function findOneByProblem(
  this: IProblemModel,
  { problem, solution }: { problem: string; solution: string }
): Promise<IProblem> {
  const record = await this.findOne({ problem, solution });
  return record;
}

export default mongoose.model('Problem', ProblemSchema);

ProblemSchema.statics.findOneByProblem = findOneByProblem;

export interface IProblemModel extends Model<IProblem> {
  findOneByProblem: (
    this: IProblemModel,
    { problem, solution }: { problem: string; solution: string }
  ) => Promise<IProblem>;
}

然而,在這些行

const record = await this.findOne({ problem, solution });
return record;

我收到一個編譯器錯誤說這個

TS2322: Type 'IProblem | null' is not assignable to type 'IProblem'.   Type 'null' is not assignable to type 'IProblem'.

我錯過了什么嗎?

您的findOneByProblem類型是錯誤的 – 畢竟,您可能沒有找到IProblem實例,結果為空。

正確的類型是

Promise<IProblem | null>

– 或者你可以在內部if(problem === null) throw new Error("No Problem found"); 如果您不想更改類型,則可以在函數中使用或類似。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM