Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

481
Vistas
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.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda