diff --git a/lib/cast.js b/lib/cast.js index 1cb88406de4..b65c1e3737b 100644 --- a/lib/cast.js +++ b/lib/cast.js @@ -264,7 +264,7 @@ module.exports = function cast(schema, obj, options, context) { } const strict = 'strict' in options ? options.strict : schema.options.strict; - const strictQuery = getStrictQuery(options, schema._userProvidedOptions, schema.options); + const strictQuery = getStrictQuery(options, schema._userProvidedOptions, schema.options, context); if (options.upsert && strict) { if (strict === 'throw') { throw new StrictModeError(path); @@ -374,7 +374,7 @@ function _cast(val, numbertype, context) { } } -function getStrictQuery(queryOptions, schemaUserProvidedOptions, schemaOptions) { +function getStrictQuery(queryOptions, schemaUserProvidedOptions, schemaOptions, context) { if ('strictQuery' in queryOptions) { return queryOptions.strictQuery; } @@ -387,5 +387,18 @@ function getStrictQuery(queryOptions, schemaUserProvidedOptions, schemaOptions) if ('strict' in schemaUserProvidedOptions) { return schemaUserProvidedOptions.strict; } + if ( + context.mongooseCollection && + context.mongooseCollection.conn && + context.mongooseCollection.conn.base && + context.mongooseCollection.conn.base.options) { + const mongooseOptions = context.mongooseCollection.conn.base.options; + if ('strictQuery' in mongooseOptions) { + return mongooseOptions.strictQuery; + } + if ('strict' in mongooseOptions) { + return mongooseOptions.strict; + } + } return schemaOptions.strictQuery; } diff --git a/test/query.test.js b/test/query.test.js index b56a5e6c3de..a5309ebba40 100644 --- a/test/query.test.js +++ b/test/query.test.js @@ -4263,4 +4263,47 @@ describe('Query', function() { ); }, { message: 'Can\'t modify discriminator key "animals.kind" on discriminator model' }); }); + + it('global strictQuery should work if applied after schema creation (gh-12703)', async() => { + const m = new mongoose.Mongoose(); + + await m.connect(start.uri); + + const schema = new mongoose.Schema({ title: String }); + + const Test = m.model('test', schema); + + m.set('strictQuery', false); + + await Test.create({ + title: 'chimichanga' + }); + await Test.create({ + title: 'burrito bowl' + }); + await Test.create({ + title: 'taco supreme' + }); + + const cond = { + $or: [ + { + title: { + $regex: 'urri', + $options: 'i' + } + }, + { + name: { + $regex: 'urri', + $options: 'i' + } + } + ] + }; + + const found = await Test.find(cond); + assert.strictEqual(found.length, 1); + assert.strictEqual(found[0].title, 'burrito bowl'); + }); });