Ktr1000
Ktr1000

Reputation: 253

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);

Upvotes: 3

Views: 2443

Answers (1)

Daniel
Daniel

Reputation: 11182

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

Upvotes: 2

Related Questions