【问题标题】:Mongoose with typescript?带有打字稿的猫鼬?
【发布时间】:2021-01-05 06:48:18
【问题描述】:

我在 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'.

我错过了什么吗?

【问题讨论】:

    标签: node.js typescript express mongoose


    【解决方案1】:

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

    正确的类型是

    Promise<IProblem | null>
    

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

    【讨论】:

      猜你喜欢
      • 2020-06-21
      • 2016-02-05
      • 2020-05-11
      • 2017-04-11
      • 2016-04-01
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      • 2021-04-26
      相关资源
      最近更新 更多