'How to use proper typescript types in mongodb find filter combined with a predefined schema?
I am using native mongodb (npmjs.com/mongodb) driver for node.js.
I've a collection with following interface:
interface Users {
name: string;
age: number;
favoriteFood: string;
}
I've to query this collection like:
const filter = { name: "lily" };
DB.collection("Users").find(filter);
Now, how will I define type of that filter variable?
I could use something like Record<string, any>. But that is vary broad.
const filter: Record<string, any>
= { nmae: "lily" }
// see the miss typed name. Gives no errors.
// but I'd like to see a little type checking there.
So I tried
const filter: Partial<Record<keyof Users, any>>
= { name: "lily" } // this force me to use the same keys as in schema.
Now is there any way I can avoid the any type in the above code? So that it support all kinds of filters and operators like $gt, $lt etc.
Solution 1:[1]
Basically, you need to import Filter type from mongodb and then simply use it.
const filter: Filter<User> = {}
For example lets say you want to create a function that receives a filter object.
function find(filter: Filter<User> = {}) {
return Db.collection<User>("users").find(filter).toArray();
}
Now you can call this functino and have the auto complete suggestion. you can also use different operators such as $in.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mr. A |
