我正在嘗試從城市物件中獲取lat&lon屬性,但出現 Typescript 錯誤
Tha JSON 模式是這樣的
{"_id":"vflv511vfsvsv51","name:"dallas","weather":{"coord":{ "lon":"-96.7836","lat": "32.7668"}}}
所以通常要訪問它們我們應該寫這樣的東西city.weather.lon
錯誤
[09:52:31] File change detected. Starting incremental compilation...
src/cities/cities.service.ts:130:30 - error TS2339: Property 'city' does not exist on type 'Mixed'.
130 const lat = city.weather.coord.lat;
~~~~~
src/cities/cities.service.ts:131:30 - error TS2339: Property 'city' does not exist on type 'Mixed'.
131 const lon = city.weather.coord.lon;
~~~~~
[09:52:32] Found 2 errors. Watching for file changes.
城市.service.ts
async GetCityWeather(cityName) {
const city = await this.cityModel.findOne({ name: cityName });
if (!city) {
this.getCityLastWeather(cityName);
}
const lat = city.weather.coord.lat;
const lon = city.weather.coord.lon;
const last7DaysWeather = this.getCityLastXDaysWeather(lat, lon);
...
}
city.model.ts
import * as mongoose from 'mongoose';
export const CitySchema = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true,
index: true,
},
weather: mongoose.SchemaTypes.Mixed,
});
export interface City {
id: mongoose.Schema.Types.ObjectId;
name: string;
weather: mongoose.Schema.Types.Mixed;
}
uj5u.com熱心網友回復:
這似乎是一個打字稿問題而不是 mongoose(雖然我覺得它weather沒有any在 ts 中定義很奇怪),你可以試試這個:
city.weather['coord']['lon']
參考: 錯誤 TS2339:型別“Y”上不存在屬性“x”
uj5u.com熱心網友回復:
如果未找到,城市名稱可能會回傳 null。為了避免這種情況,我建議您將城市全部降低并修剪空間以使搜索更準確。
const city = await this.cityModel.findOne({ name: cityName.toLowerCase().trim() });
//save city name in db also as name.toLowerCase().trim()
if (!city) {
this.getCityLastWeather(cityName);
}
const lat = city.weather.coord.lat;
const lon = city.weather.coord.lon;
const last7DaysWeather = this.getCityLastXDaysWeather(lat, lon);
...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/392586.html
