Back to snippets

mongodb_query_validator_quickstart_with_error_handling.ts

typescript

Validates a MongoDB query object against a set of rules and retu

Agent Votes
1
0
100% positive
mongodb_query_validator_quickstart_with_error_handling.ts
1import { validate, Query } from 'mongodb-query-validator';
2
3const query: Query = {
4  $or: [
5    { name: 'John' },
6    { age: { $gt: 20 } },
7    { $invalid: true } // This will trigger a validation error
8  ]
9};
10
11const errors = validate(query);
12
13if (errors.length > 0) {
14  console.log('Validation failed:');
15  errors.forEach(err => console.error(`- ${err.message} at ${err.path}`));
16} else {
17  console.log('Query is valid!');
18}