typescript - 错误 TS2339 : Property 'coord' does not exist on type 'Mixed'

标签 typescript mongodb mongoose nestjs mongoose-schema

我尝试从城市对象获取latlon 属性,但收到 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']

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

关于typescript - 错误 TS2339 : Property 'coord' does not exist on type 'Mixed' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70471326/

相关文章:

node.js - MongoDB/Mongoose 有很多关系

node.js - 尝试通过 mongoose 使用 Node js 将对象保存在文档上时出现问题

typescript - 当使用 AWS CDK 创建 cfn 模板和管道时,如何使用 CodePipeline 部署 CloudFormation 堆栈?

typescript - 除非提供 --module 标志,否则无法编译模块

typescript - VSCode - 设置带有 Deno(后端)文件夹和 Vite(前端)文件夹的 monorepo

java - 仅保留 Mongo 集合中的唯一值——子数组

尝试使用 MongoDB BulkWriteOperation 时出现 java.lang.IllegalStateException

node.js - 存储高频、周期性时间序列数据的最佳方式?

javascript - 预渲染与实时 Canvas 渲染时的奇怪结果

node.js - Mongoose 内连接