如何使用mongodb解决打字稿问题

时间:2020-10-11 19:45:38

标签: mongodb typescript

我对此代码有疑问

    const doc = await req.db
      .collection('clients')
      .find({}, { lName: 1, fName: 1, id: 1 })

出现打字错误

Type error: Argument of type '{ lName: number; fName: number; id: number;  }' is not assignable to parameter of type 'FindOneOptions<any>'.

我该如何解决?谢谢!

1 个答案:

答案 0 :(得分:1)

解决方案

这应该为您解决:

const doc = await req.db
    .collection<Client>('clients')
    .find({ lName: "", fName: "", id: 1 })

说明

.find()的{​​{1}}方法采用一个或两个选项,其中第一个选项为Db,第二个选项为FilterQuery

FindOneOptions

第二个参数的optionsfind<T = TSchema>(query?: FilterQuery<TSchema>): Cursor<T>; find<T = TSchema>(query: FilterQuery<TSchema>, options?: FindOneOptions<T extends TSchema ? TSchema : T>): Cursor<T>; sort之类的东西,而不是要查找的对象。第二个参数中的内容是limit,它必须是第一个参数。

FilterQuery类型是泛型的,因此,为了使Typescript知道我们正在过滤客户端,我们需要在调用FilterQuery时传递泛型。这将导致它返回collection<Client>('clients')的集合。

这是我使用的界面,但我确定还有更多属性

Client

现在,如果您将无效的类型传递给interface Client { lName: string; fName: string; id: number; } ,则打字稿会知道并会抛出错误。

.find()

这是一个错误,因为我说.find({ lName: 1, fName: 1, id: 1 }) fName必须是lName

Typescript Playground Link