Query Casting
When you execute the query using Query#exec()
or , Mongoose casts the filter to match your schema.
// Note that `_id` and `age` are strings. Mongoose will cast `_id` to
// a MongoDB ObjectId and `age.$gt` to a number.
const query = Character.findOne({
_id: '5cdc267dd56b5662b7b7cc0c',
age: { $gt: '50' }
});
// `{ _id: '5cdc267dd56b5662b7b7cc0c', age: { $gt: '50' } }`
const doc = await query.exec();
doc.name; // "Jean-Luc Picard"
// Mongoose casted the filter, so `_id` became an ObjectId and `age.$gt`
// became a number.
query.getFilter()._id instanceof mongoose.Types.ObjectId; // true
typeof query.getFilter().age.$gt === 'number'; // true
By default, Mongoose does not cast filter properties that aren’t in your schema.
const query = Character.findOne({ notInSchema: { $lt: 'not a number' } });
// 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'
:
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; // 'StrictModeError'
// Path "notInSchema" is not in schema and strictQuery is 'throw'.