Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set strictQuery to false on a find method level

Mongoose 6 introduced many changes, and the most important change was the strict and strictQuery for the search queries, they are equal to true by default.

https://mongoosejs.com/docs/migrating_to_6.html#strictquery-is-removed-and-replaced-by-strict

I have a schema like this:

const mySchema = new mongoose.Schema({
    name: String
})

And I have a document like the following in the database:

{
   name: "Murat",
   _archived: true
}

as You can see, the field _archived does not exist in the schema.

Now If I wanted to:

const archivedDocs = await myModel.find({ _archived: true })

I can't because of the new update.

Mongoose says that if you wanted to perform this search query, you can add the strictQuery option to your schema and set it to true.

However, I don't want to do that, because this will have an effect everywhere. I only want to allow this one find() line of code to pass this checking.

Is there something in mongoose that I can do like:

const archivedDocs = await myModel.find({ _archived: true }, { strictQuery: false })

??

like image 865
Islam Y- Avatar asked Sep 10 '25 12:09

Islam Y-


1 Answers

Yes the same "workaround" for the findOne will work for the find method.

they both receive the same options in the same order: filter, projection then options. So when you provide options = { strictQuery: false } to the findOne method it works. the same exact syntax will work for the find, like so:

const archivedDocs = await myModel.find({ _archived: true }, null, { strictQuery: false })
like image 90
Tom Slabbaert Avatar answered Sep 13 '25 04:09

Tom Slabbaert