【问题标题】:mongoose typescript type for updateOneupdateOne 的猫鼬打字稿类型
【发布时间】:2021-05-27 22:22:10
【问题描述】:

我有以下代码:

async setProcessedSubUser(id: ObjectId, processSub: ProcessSubscriptionInterface): Promise<???> {
  return this.userModel.updateOne({ _id: id }, { inProcessSubscription: processSub });
}

执行查询时,响应类似于{ n: 1, nModified: 1, ok: 1 }

如果我这样调用我的函数:

return this.userService.setProcessedSubUser(YYY, XXX)
    .then((response) => {
      if (response.nModified !== 1) // error
      return response;
    })

代码崩溃是因为nModified dosen't exist on response

我需要用什么类型代替???

【问题讨论】:

    标签: typescript mongoose


    【解决方案1】:

    只需创建setProcessedSubUser函数返回的接口即可。

    
    interface IUpdateOne {
      n: number;
      nModified: number;
      ok: number;
    }
    
    async setProcessedSubUser(id: ObjectId, processSub: ProcessSubscriptionInterface): Promise<IUpdateOne> {
      return this.userModel.updateOne({ _id: id }, { inProcessSubscription: processSub });
    }
    

    【讨论】:

    • 我这样做但我搜索“真正的”猫鼬类型响应(如果这种类型当然存在)
    • 如果你看一下@types/mongoose包,你可以看到类型定义如下。他们将响应定义为 raw 类型为 any 。 updateOne(条件: FilterQuery, doc: UpdateQuery, callback?: (err: any, raw: any) => void): Query & QueryHelpers; updateOne(conditions: FilterQuery, doc: UpdateQuery, options: ModelUpdateOptions, callback?: (err: any, raw: any) => void): Query & QueryHelpers;
    猜你喜欢
    • 2020-05-11
    • 2017-01-20
    • 1970-01-01
    • 2016-02-05
    • 2017-04-11
    • 2016-04-01
    • 1970-01-01
    • 2021-01-05
    • 2018-10-09
    相关资源
    最近更新 更多