我無法為以下從 mongodb 回傳值的函式定義正確的型別:
export const getPopulatedCountriesByCountryIdsDB = async (countryIds: any[]) => {
try {
const query = {
id: {$in: countryIds}
}
const db = await getDb();
const collectionName = process.env.MONGO_DB_COLLECTION_POPULATED_COUNTRY!;
const countries = await db?.collection(collectionName).find<Country>(query).toArray();
return countries;
} catch (err) {
logger.error('Error in getPopulatedCountriesByCountryIdsDB:', err);
}
}
介面Country定義如下:
export interface Country {
id: ObjectId;
cities: []
};
我呼叫它如下:
const countries = await getPopulatedCountriesByCountryIdsDB(countriesIds!);
但后來,當我嘗試訪問一些嵌套屬性時,如下所示:
const country = countries!.filter((country: any) => country.id === countryId);
const cities = country.cities.filter((city: any) => city.id === cityId);
我收到以下錯誤:
“國家 []”型別不存在屬性“城市”
如何正確定義型別Country?謝謝!
更新: 在catS發表評論后,我將代碼更新如下:
國家型別:
export interface Country {
id: ObjectId;
cities: any[]
};
但是得到以下錯誤:
“國家 []”型別不存在屬性“城市”
更新1:如果我使用它而不在這里將型別傳遞給這個函式:
const countries = await db?.collection(collectionName).find(query).toArray();
我收到以下錯誤:
型別“WithId[]”上不存在屬性“城市”。
uj5u.com熱心網友回復:
“國家 []”型別不存在屬性“城市”
出現此錯誤是因為您將陣列過濾為一個元素,然后嘗試從該陣列中讀取屬性。相反,您需要從陣列中獲取一個元素,然后從該元素中讀取屬性。
const country = countries!.filter((country: any) => country.id === countryId);
// at this point country is a list containing one element
// read out the first value
const selectedCountry = country[0]
const cities = selectedCountry.cities.filter((city: any) => city.id === cityId);
如果陣列為空,您將需要一些錯誤處理 - 即如果 countryId 不匹配任何 country.id。
在使用所選城市時,您還需要執行相同的程序。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/523952.html
上一篇:使用Mac安裝3.11版本后,如何確保更新我的Python版本?
下一篇:傳播物件并添加標志node.js
