当试图找到我的用户模型时,我得到:对象可能为“空” 如果可能的话,我宁愿不禁止 typescript 的严格规则。
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);
最佳答案
问题是您的 if 语句 if (!user)
没有处理如果用户为 null/undefined 时应该发生的事情。
如果您选择在用户为空(或未定义)的情况下从函数返回
if (!user) {
return
}
TypeScript 足够聪明,可以意识到一旦到达 passwordMatch 行,用户就永远不会为 null
关于typescript - 带有 typescript 的 Mongoose :Object is possibly null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55770787/