【问题标题】:Type is inferred as any with find moongose typescript使用 find mongoose typescript 推断类型为 any
【发布时间】:2021-01-20 07:08:20
【问题描述】:

我的models/areas.ts 文件中有以下内容:

import { Document, model, Schema } from 'mongoose'
import uniqueValidator from 'mongoose-unique-validator'

interface IAreas extends Document {
  abstract: string,
  code    : number,
  image   : string,
  name    : string
}

const Areas = new Schema(
  {
    abstract: {
      required: true,
      type    : String
    },
    code: {
      default: 1,
      type   : Number
    },
    image: {
      default: '',
      type   : String
    },
    name: {
      required: true,
      type    : String,
      unique  : true
    }
  }
)

Areas.plugin(uniqueValidator)

const AreasModel = model<IAreas>('areas', Areas)

export { AreasModel, IAreas }

我的controller/areas.ts 文件中有以下内容:

import { AreasModel, IAreas } from '../models/areas'

const getAll = async (): Promise<IAreas[]> => {
  try {
    const areas = await AreasModel.find({}, '-__v')

    return areas
  } catch (error) {
    console.log('There was a problem trying to get all the areas.')
    throw error
  }
}

所以,我遇到的问题是 areas 变量被推断为任何变量,我不知道为什么,我有其他项目被正确推断。

这里是我正在使用的版本:

typescript: ^4.1.3
ts-node: ^9.1.1
mongoose: ^5.11.12
@types/mongoose: ^5.10.3

【问题讨论】:

  • 你的 getAll 是否有一个未播种的 await 或者它不应该返回一个承诺?
  • 这是一个代码拼写错误。我已经纠正了。您指的是没有异步的await,对吧?
  • 嗯.. 不确定我对 JS 的了解是否足够,我会删除 async 和 Promise 类型

标签: node.js typescript mongoose


【解决方案1】:

好吧,解决我的问题的方法是删除 @types/mongoose@types/mongoose-unique-validator 包。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-03
    • 2021-03-24
    • 1970-01-01
    • 2019-09-17
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    相关资源
    最近更新 更多