使用 Typescript 时的 MongoDB FindOptions

Seb*_*ine 8 mongodb typescript

我正在将 JS 项目转换为 TS,并且在查询集合时遇到 FindOptions 问题。我只想获取集合中所有元素的 ID。这是导致 TS 错误的 TS 代码:

import { Collection, Db, Document, MongoClient } from "mongodb";

type MyDoc = {
    _id: object,
    title: string,
    image: string,
    description: string
} 
    
const client: MongoClient = await MongoClient.connect("mongodb://127.0.0.1:27017");
const db: Db = client.db("mydb");
const myCollection: Collection<MyDoc> = db.collection("myCollection");
const ids: object[] = await myCollection.find({}, { _id: 1 }).toArray();
client.close();
Run Code Online (Sandbox Code Playgroud)

问题在于{_id: 1}FindOption 在 JS 中工作正常。这是错误消息:

Argument of type '{ _id: number; }' is not assignable to parameter of type 'FindOptions<Document>'.
      Object literal may only specify known properties, and '_id' does not exist in type 'FindOptions<Document>'.
Run Code Online (Sandbox Code Playgroud)

Yon*_*hun 10

来自find(Mongo 文档)

find<T>(filter: Filter<T>, options?: FindOptions<T>): FindCursor<T>
Run Code Online (Sandbox Code Playgroud)

第二个参数必须是FindOptions<T>类型。

您需要将FindOptions<T>类型值传递给第二个参数,并使用FindOptions.projection来指定返回字段。

投影: 投影

查询中要返回的字段。要包含或排除的字段对象(其中之一,而不是两者),{'a':1, 'b': 1} 或 {'a': 0, 'b': 0}

const ids: object[] = await myCollection.find({}, { projection: { _id: 1 } }).toArray();
Run Code Online (Sandbox Code Playgroud)