Query Casting

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

    1. // Note that `_id` and `age` are strings. Mongoose will cast `_id` to
    2. // a MongoDB ObjectId and `age.$gt` to a number.
    3. const query = Character.findOne({
    4. _id: '5cdc267dd56b5662b7b7cc0c',
    5. age: { $gt: '50' }
    6. });
    7. // `{ _id: '5cdc267dd56b5662b7b7cc0c', age: { $gt: '50' } }`
    8. const doc = await query.exec();
    9. doc.name; // "Jean-Luc Picard"
    10. // Mongoose casted the filter, so `_id` became an ObjectId and `age.$gt`
    11. // became a number.
    12. query.getFilter()._id instanceof mongoose.Types.ObjectId; // true
    13. typeof query.getFilter().age.$gt === 'number'; // true

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

    1. const query = Character.findOne({ notInSchema: { $lt: 'not a number' } });
    2. // No error because `notInSchema` is not defined in the schema

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

    1. mongoose.deleteModel('Character');
    2. const schema = new mongoose.Schema({ name: String, age: Number }, {
    3. strictQuery: 'throw'
    4. });
    5. Character = mongoose.model('Character', schema);
    6. const query = Character.findOne({ notInSchema: { $lt: 'not a number' } });
    7. const err = await query.exec().then(() => null, err => err);
    8. err.name; // 'StrictModeError'
    9. // Path "notInSchema" is not in schema and strictQuery is 'throw'.

    Implicit $in