繁体   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