猫鼬与打字稿?

时间:2020-09-18 10:23:04

标签: node.js typescript express mongoose

我在nodejs和打字稿中有一个项目。我正在使用猫鼬连接到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'.

我想念什么吗?

1 个答案:

答案 0 :(得分:3)

您为findOneByProblem输入的类型是错误的-毕竟,您可能找不到IProblem实例,结果为空。

正确的类型是

Promise<IProblem | null>

–或者,如果您不想更改类型,则可以在内部使用if(problem === null) throw new Error("No Problem found");或类似的函数。