【问题标题】:error TS2339: Property 'coord' does not exist on type 'Mixed'错误 TS2339:“混合”类型上不存在属性“坐标”
【发布时间】:2022-01-24 23:49:30
【问题描述】:

我正在尝试从 city 对象中获取 latlon 属性,但出现 Typescript 错误

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.

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;
}

【问题讨论】:

  • 如果您的查询中没有任何城市,您的 city 对象可能是 null
  • 是的,我注意到了,我用 createCity() 替换了 getCityWeather()。谢谢!

标签: typescript mongodb mongoose nestjs mongoose-schema


【解决方案1】:

这似乎是一个打字稿问题而不是猫鼬(虽然我觉得很奇怪 weather 在 ts 中没有定义为 any ),你可以试试这个:

city.weather['coord']['lon']

参考: error TS2339: Property 'x' does not exist on type 'Y'

【讨论】:

  • 谢谢@Med-AmineBenyettou
【解决方案2】:

如果未找到,城市名称可能会返回 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);
...
}

【讨论】:

    猜你喜欢
    • 2021-06-22
    • 2019-01-21
    • 2016-08-13
    • 2017-12-20
    • 2016-11-14
    • 2017-10-24
    • 2021-08-10
    • 2018-11-17
    • 2020-09-25
    相关资源
    最近更新 更多