Skip to content

Documentation / @andrew_l/search-query-language / parseToMongoose

Function: parseToMongoose()

parseToMongoose(reference, input, options?): Record<string, any>

Parses a query string and converts it into a MongoDB-compatible query object, using a provided Mongoose schema or model for field validation and transformation.

Parameters

reference: MongooseSchema | MongooseModel

The Mongoose schema or model used to infer field types and transformations.

input: string

The query string to be parsed.

options?: ParseToMongoOptions = {}

Optional configuration for parsing behavior.

Returns

Record<string, any>

  • The MongoDB query representation.

Examples

ts
// Type transformations are automatically inferred from the schema.
const schema = new mongoose.Schema({
  age: { type: Number },
});

const query = parseToMongoose(schema, '_id = "67d737b73af3ff3e00a3bbf1"');
console.log(query);
// Output: { _id: new ObjectId("67d737b73af3ff3e00a3bbf1") }
ts
// Complex queries with logical operators
const schema = new mongoose.Schema({
  age: { type: Number },
  customer: {
    name: { type: String },
    active: { type: Boolean },
  }
});

const query = parseToMongoose(schema, 'customer.active = true AND age >= 18');
console.log(query);
// Output: { $and: [{ 'customer.active': true }, { age: { $gte: 18 } }] }

Throws

If the input query contains invalid syntax or references disallowed fields.