Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

482
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda