Reputation: 35720
Here is my schema:
const Post = mongoose.model('Post', {
title: String,
authorId: String,
})
I'd like to query it with:
Post.find({ authorId: '123', someField: 1 })
which results in []
, how can I make mongoose ignore query fields not in the schema?
Upvotes: 3
Views: 1735
Reputation: 144
There is a flag strictQuery
for it (https://mongoosejs.com/docs/guide.html#strictQuery)
For backwards compatibility, the
strict
option does not apply to thefilter
parameter for queries. Mongoose has a separatestrictQuery
option to toggle strict mode for thefilter
parameter to queries.
const mySchema = new Schema({ field: Number }, {
strict: true,
strictQuery: true // Turn on strict mode for query filters
});
const MyModel = mongoose.model('Test', mySchema);
// Mongoose will strip out `notInSchema: 1` because `strictQuery` is `true`
MyModel.find({ notInSchema: 1 });
Upvotes: 2