【问题标题】:TypeScript thinks mongoose lean returns an arrayTypeScript 认为 mongoose 精益返回一个数组
【发布时间】:2020-08-06 15:27:54
【问题描述】:

我正在尝试使用 typescript / mongoose 制作一个通用的 crud 控制器,但遇到了类型问题,如果我执行以下操作,它可以正常工作:

async findOne<T>(id: number): Promise<T> {
    return this._collection.findOne({ _id: id }, null, { lean: true });
}

但是使用 .lean() 会产生类型错误,即使结果相同(据我所知):

async findOne<T>(id: number): Promise<T> {
    return this._collection.findOne({ _id: id }).lean();
}

它认为 .lean() 可以返回 T 或 T[]。

万一这对于 findOne() 来说是正常的,我对 findById 也有同样的问题,我认为它只能返回一个对象:

async findById<T>(id: number): Promise<T> {
    return this._collection.findById(id).lean(); // error
    // return this._collection.findById(id, null, {lean: true}); <-- works
}

这里有什么区别/问题?

【问题讨论】:

    标签: typescript generics mongoose


    【解决方案1】:

    您可以显式确定lean 函数的返回值

    async findOne<T>(id: number): Promise<T> {
        return this._collection.findOne({ _id: id }).lean<T>();
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-26
      • 2019-04-27
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 2012-12-20
      相关资源
      最近更新 更多