Skip to content

Commit

Permalink
Merge pull request #12485 from Automattic/vkarpov15/gh-12325
Browse files Browse the repository at this point in the history
fix(query): treat `findOne(_id)` as equivalent to `findOne({ _id })`
  • Loading branch information
vkarpov15 committed Sep 30, 2022
2 parents 83c8002 + a40844e commit 76894b4
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
4 changes: 4 additions & 0 deletions lib/query.js
Expand Up @@ -2402,6 +2402,10 @@ Query.prototype.merge = function(source) {

utils.merge(this._mongooseOptions, source._mongooseOptions);

return this;
} else if (this.model != null && source instanceof this.model.base.Types.ObjectId) {
utils.merge(this._conditions, { _id: source }, opts);

return this;
}

Expand Down
5 changes: 3 additions & 2 deletions test/helpers/update.castArrayFilters.test.js
Expand Up @@ -2,6 +2,7 @@

const Query = require('../../lib/query');
const Schema = require('../../lib/schema');
const Types = require('../../lib/types');
const assert = require('assert');
const castArrayFilters = require('../../lib/helpers/update/castArrayFilters');

Expand Down Expand Up @@ -231,7 +232,7 @@ describe('castArrayFilters', function() {
});
let q = new Query();
q.schema = schema;
q.model = { base: { options: { strictQuery: false } } };
q.model = { base: { Types, options: { strictQuery: false } } };

let p = { 'arr.$[arr].id': 42 };
let opts = {
Expand All @@ -247,7 +248,7 @@ describe('castArrayFilters', function() {

q = new Query();
q.schema = schema;
q.model = { base: { options: { strictQuery: true } } };
q.model = { base: { Types, options: { strictQuery: true } } };

p = { 'arr.$[arr].id': 42 };
opts = {
Expand Down
16 changes: 16 additions & 0 deletions test/query.test.js
Expand Up @@ -4132,4 +4132,20 @@ describe('Query', function() {
assert.equal(item.get('select.key.some'), 'value');
assert.equal(item.doNotSelect, undefined);
});

it('treats ObjectId as object with `_id` for `merge()` (gh-12325)', async function() {
const testSchema = new mongoose.Schema({ name: String });
const Test = db.model('Test', testSchema);
const _id = new mongoose.Types.ObjectId();

let q = Test.find(_id);

assert.ok(q.getFilter()._id instanceof mongoose.Types.ObjectId);
assert.equal(q.getFilter()._id.toHexString(), _id.toHexString());

q = Test.findOne(_id);

assert.ok(q.getFilter()._id instanceof mongoose.Types.ObjectId);
assert.equal(q.getFilter()._id.toHexString(), _id.toHexString());
});
});

0 comments on commit 76894b4

Please sign in to comment.