0

I have an issue with this code

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

giving the typescript error

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

how can I fix this? thanks!

1 Answer 1

1

Solution

This should resolve it for you:

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

Explaination

The .find() method of Db takes one or two options, where the first option is the FilterQuery and the second is FindOneOptions.

find<T = TSchema>(query?: FilterQuery<TSchema>): Cursor<T>;
find<T = TSchema>(query: FilterQuery<TSchema>, options?: FindOneOptions<T extends TSchema ? TSchema : T>): Cursor<T>;

The options for the second argument are things like sort and limit, not the object to find. What you have in the second argument is the FilterQuery which needs to be the first argument.

The FilterQuery type is generic, so in order for typescript to know that we are filtering clients, we need to pass the generic when calling collection<Client>('clients'). That will cause it to return a collection of Client.

This is the interface I used, but I'm sure there are more properties

interface Client {
    lName: string;
    fName: string; 
    id: number;
}

Now, if you pass an invalid type to .find(), typescript knows and will throw and error.

.find({ lName: 1, fName: 1, id: 1 })

This is now an error because I said that fName and lName must be string.

Typescript Playground Link

Sign up to request clarification or add additional context in comments.

1 Comment

In your find you aren't returning all fields. .find({ lName: 1, fName: 1, id: 1 }) needs to be .find({}, { lName: 1, fName: 1, id: 1 }) to have ALL ENTRIES returned while only selecting certain fields from EVERY entry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.