Search code examples
typescriptmongodbmongoosenestjsmongoose-schema

error TS2339: Property 'coord' does not exist on type 'Mixed'


I am trying to get the lat & lon properties from city object, but I get a Typescript error

Tha JSON schema is like this {"_id":"vflv511vfsvsv51","name:"dallas","weather":{"coord":{ "lon":"-96.7836","lat": "32.7668"}}} so normally to access them we should write something like this city.weather.lon

Error

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

Solution

  • It seems like a typescript problem instead of mongoose (Although I find it strange that weather is not defined as any in ts ), you can try this:

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

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