我試圖了解為什么我無法從用戶檔案訪問某些屬性。在為用戶檔案查詢資料庫時,我想訪問它的屬性。
我的用戶模型:
import mongoose from 'mongoose';
export interface IUser extends mongoose.Document {
email: string;
password: string;
}
const UserSchema = new mongoose.Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
});
export default mongoose.model<IUser>('User', UserSchema);
查詢:
const user = User.findById(payload.sub);
const { email } = user;
這是我得到的打字稿錯誤:
Property 'email' does not exist on type 'Query<(IUser & { _id: ObjectId; }) | null, IUser & { _id: ObjectId; }, {}, IUser>'.
我不明白為什么會收到此錯誤。我似乎也無法訪問 _id 屬性。
uj5u.com熱心網友回復:
查詢資料庫是一個異步程序。Mongoose 實際上不會直接回傳一個 Promise,而是它自己的擴展 Promise 的類。但是,您仍然可以使用await等待它解決:
const user = await User.findById(payload.sub);
if (!user) { /* ??? */ } // no user found
const { email } = user;
null您還應該檢查用戶是否存在,因為如果沒有找到這樣的用戶,此方法也可以回傳。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/524247.html
上一篇:在地圖中使用updateOne,將過濾器設定為唯一的id,$set是檔案,而upsert是true。即使這樣,也會創建新檔案
