尝试查找我的用户模型时,我得到:对象可能为“ null” 如果可能的话,我宁愿不禁止打字稿的严格规定。
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);
答案 0 :(得分:1)
问题是,如果用户为null / undefined,则if语句public class ApiServices
{
public string JsonResult { get; private set; }
public async Task<bool> RegisterUserAsync(string email, string name, /*string first_name, string last_name,*/ string password)
{
var client = new HttpClient();
var model = new RegisterBindingModel
{
Email = email,
//FirstName = first_name,
//LastName = last_name,
Name = name,
Password = password,
};
var json = JsonConvert.SerializeObject(model);
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync("https://myurl/v1/auth/register", httpContent);
if (response.IsSuccessStatusCode)
{
var result = JsonConvert.DeserializeObject(JsonResult);
return true;
}
return false;
}
public async Task<string> LoginAsync(string email, string password)
{
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("email", email),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("grant_type", "password")
};
var request = new HttpRequestMessage(HttpMethod.Post, "https://myurl/auth/login" + "Token");
request.Content = new FormUrlEncodedContent(keyValues);
var client = new HttpClient();
var response = await client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
JObject jwtDynamic = JsonConvert.DeserializeObject<dynamic>(content);
var accessTokenExpiration = jwtDynamic.Value<DateTime>(".expires");
var accessToken = jwtDynamic.Value<string>("access_token");
//Settings.AccessTokenExpirationDate = accessTokenExpiration;
Debug.WriteLine(accessTokenExpiration);
Debug.WriteLine(content);
return accessToken;
}
}
无法处理应该发生的情况。
如果用户选择null(或未定义),则选择从函数返回
if (!user)
TypeScript非常聪明,可以认识到一旦进入passwordMatch行,用户将永远不会为空