Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

474
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!