Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose with Typescript:Object is possibly null

When trying to find my user model I get: Object is possibly 'null' If possible I would prefer not suppressing typescript's strict rule.

const { email, password } = req.body;
const user = await User.findOne({ email:email });
if (!user) {
}
/// This line causes the error
const passwordMatch = await bcrypt.compare(password, user.password);

////User Interface

import { Document } from 'mongoose';
interface User extends Document {
  email: string;
  password: string;
  username: string;
}
export default User;


////User Schema

import mongoose, { Document, Schema, Model, model } from 'mongoose';
import User from '../interfaces/User';

const UserSchema: Schema = new Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  username: { type: String, required: true },
});
export default mongoose.model<User>('User', UserSchema);
like image 887
Ktr1000 Avatar asked Aug 07 '26 23:08

Ktr1000


1 Answers

The problem is that your if statement if (!user) is not handling what should happen if the user is null/undefined.

If you choose to return from the function in case the user is null (or undefined) with

if (!user) {
  return
}

TypeScript is clever enough to realize that once you get to the passwordMatch line, the user will never be null

like image 109
Daniel Avatar answered Aug 09 '26 13:08

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!