Type-checking in mongoDB filter with sub-objects

37 Views Asked by At

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

1

There are 1 best solutions below

1
Atique On

If i am understanding the question correctly. Two possible things you might want to do with type check.

  1. You want the input username is strictly typed.
const username: string = 'user1' || '';

this will ensure that you're not passing null value to username, which can lead to COLLSCAN.

  1. If you want that the returned value is also type correct.
const users: User[] = await collection.find<User>({ 'userData.username': username }).toArray();

this way you will get the type safe data as return value.