Global "strictQuery: false" doesn't work for existing models
Prerequisites
- [X] I have written a descriptive issue title
- [X] I have searched existing issues to ensure the bug has not already been reported
Mongoose version
6.5.2
Node.js version
14.20.0
MongoDB server version
5.0.8
Description
Setting strictQuery to false only works for models created after calling mongoose.set('strictQuery', false).
Steps to Reproduce
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
// calls model() before set()
const Cat = mongoose.model('Cat', { name: String });
mongoose.set('strictQuery', false);
// calls model() after set()
const Dog = mongoose.model('Dog', { name: String });
Promise.all([
Cat.create({ name: 'Bob' }),
Dog.create({ name: 'Bob' }),
])
.then(() => Promise.all([
Cat.findOne({ notInSchema: 'x' }),
Dog.findOne({ notInSchema: 'x' }),
]))
.then(([cats, dogs]) => {
console.log('cats', cats) // prints doc
console.log('dogs', dogs) // prints null
return mongoose.connection.close()
});
Expected Behavior
I expected strictQuery to be false also for models created before calling mongoose.set('strictQuery', false) because usually models are imported before setting global mongoose variables.
Did you find a place to put it so it works for all schemas? I have the same problem. It doesn't work if I put it right at the beginning of my app/server file.
Edit: Ok it works now after putting it before I load my routes files (which in turn load the mongoose schema modules). Duh.
@florianwalther-private that is also how I managed to make it work. I run set('strictQuery', false) after importing mongoose and before importing any other module.
Expected behavior