wong2
wong2

Reputation: 35720

Mongoose query ignore fields not in schema

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

Answers (1)

Denis Zavershinskiy
Denis Zavershinskiy

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 the filter parameter for queries. Mongoose has a separate strictQuery option to toggle strict mode for the filter 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

Related Questions