Query Casting

The first parameter to Model.find() , Query#find() , Model.findOne() , etc. is called filter . In older content this parameter is sometimes called query or conditions . For example:

const query = Character.find({ name: 'Jean-Luc Picard' }); query.getFilter(); query.find({ age: { $gt: 50 } }); query.getFilter();

When you execute the query using Query#exec() or Query#then() , Mongoose casts the filter to match your schema.

const query = Character.findOne({ _id: '5cdc267dd56b5662b7b7cc0c' , age: { $gt: '50' } }); query.getFilter(); const doc = await query.exec(); doc.name; query.getFilter()._id instanceof mongoose.Types.ObjectId; typeof query.getFilter().age.$gt === 'number' ;

If Mongoose fails to cast the filter to your schema, your query will throw a CastError .

const query = Character.findOne({ age: { $lt: 'not a number' } }); const err = await query.exec().then(() => null , err => err); err instanceof mongoose.CastError; err.message;

The strictQuery Option

By default, Mongoose does not cast filter properties that aren't in your schema.

const query = Character.findOne({ notInSchema: { $lt: 'not a number' } }); await query.exec();

You can configure this behavior using the strictQuery option for schemas. This option is analagous to the strict option. Setting strictQuery to true removes non-schema properties from the filter:

mongoose.deleteModel( 'Character' ); const schema = new mongoose.Schema({ name: String , age: Number }, { strictQuery: true }); Character = mongoose.model( 'Character' , schema); const query = Character.findOne({ notInSchema: { $lt: 'not a number' } }); await query.exec(); query.getFilter();

To make Mongoose throw an error if your filter has a property that isn't in the schema, set strictQuery to 'throw' :

mongoose.deleteModel( 'Character' ); const schema = new mongoose.Schema({ name: String , age: Number }, { strictQuery: 'throw' }); Character = mongoose.model( 'Character' , schema); const query = Character.findOne({ notInSchema: { $lt: 'not a number' } }); const err = await query.exec().then(() => null , err => err); err.name; err.message;

Implicit $in

Because of schemas, Mongoose knows what types fields should be, so it can provide some neat syntactic sugar. For example, if you forget to put $in on a non-array field, Mongoose will add $in for you.