我尝试从城市对象获取lat
和lon
属性,但收到 Typescript 错误
JSON 模式是这样的
{"_id":"vflv511vfsvsv51","名称:"达拉斯","天气":{"坐标":{ "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.
cities.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;
}
最佳答案
这似乎是一个 typescript 问题,而不是 Mongoose 问题(虽然我觉得很奇怪 weather
没有在 ts 中定义为 any
),你可以尝试这个:
city.weather['coord']['lon']
关于typescript - 错误 TS2339 : Property 'coord' does not exist on type 'Mixed' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70471326/