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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With