i'm using MongoDB, and i want to filter a specific field on an object maintaining the type-checks with typescript.
The object is composed like this:
interface User {
_id: string;
userData: {
username: string;
email: string;
age: number;
};
// Other fields
}
And, if I want to filter by userName, I do:
const users: User[] = await collection.find({ 'userData.username': username }).toArray();
But filtering like this, leads to the impossibility to maintain the type-checks of the objects.
Eg: if I change the interface to this:
interface User {
_id: string;
userData: {
user_name: string;
email: string;
age: number;
};
// Other fields
}
typescript won't show me the type-error of userData.username
How can I solve this? Thanks
If i am understanding the question correctly. Two possible things you might want to do with type check.
this will ensure that you're not passing null value to username, which can lead to COLLSCAN.
this way you will get the type safe data as return value.