Home > Software design >  MongoDB FindOptions when using Typescript
MongoDB FindOptions when using Typescript

Time:10-10

I am converting a JS project to TS and am struggling with FindOptions when I am querying a collection. I just want to get the Ids of all elements of a collection. This is the TS code that is causing TS errors:

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();

The problem there is the {_id: 1} FindOption that is working fine in JS. This is the error message:

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>'.

CodePudding user response:

From find (Mongo docs),

find<T>(filter: Filter<T>, options?: FindOptions<T>): FindCursor<T>

The second parameter has to be FindOptions<T> type.

You need to pass value of FindOptions<T> type to second parameter and with FindOptions.projection to specify the return field(s).

projection: Projection

The fields to return in the query. Object of fields to either include or exclude (one of, not both), {'a':1, 'b': 1} or {'a': 0, 'b': 0}

const ids: object[] = await myCollection.find({}, { projection: { _id: 1 } }).toArray();
  • Related