Reputation: 1371
I have a project in nodejs and typescript. I'm using mongoose to connect to a mongoDb database. My code looks like this
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>;
}
However, at these lines
const record = await this.findOne({ problem, solution });
return record;
I get a compiler error saying this
TS2322: Type 'IProblem | null' is not assignable to type 'IProblem'. Type 'null' is not assignable to type 'IProblem'.
Am I missing something?
Upvotes: 0
Views: 189
Reputation: 169388
Your type for findOneByProblem
is wrong – after all, it's possible that you don't find an IProblem
instance, and the result is null.
The correct type is
Promise<IProblem | null>
– or you could internally if(problem === null) throw new Error("No Problem found");
or similar in the function if you don't want to change the type.
Upvotes: 3