Skip to content

Commit 18ca142

Browse files
authored
Merge pull request #15928 from Automattic/vkarpov15/fix-doc-updateone
fix(document): avoid 'Cannot mix array and object updates' on doc.updateOne() with pipeline
2 parents a88b4d9 + 1971e9b commit 18ca142

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

lib/query.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4032,7 +4032,13 @@ Query.prototype._mergeUpdate = function(update) {
40324032
}
40334033
} else if (Array.isArray(update)) {
40344034
if (!Array.isArray(this._update)) {
4035-
throw new MongooseError('Cannot mix array and object updates');
4035+
// `_update` may be empty object by default, like in `doc.updateOne()`
4036+
// because we create the query first, then run hooks, then apply the update.
4037+
if (this._update == null || utils.isEmptyObject(this._update)) {
4038+
this._update = [];
4039+
} else {
4040+
throw new MongooseError('Cannot mix array and object updates');
4041+
}
40364042
}
40374043
this._update = this._update.concat(update);
40384044
} else {

test/document.test.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15127,6 +15127,28 @@ describe('document', function() {
1512715127
await user.validate(null);
1512815128
await assert.rejects(() => user.validate({}), /Path `test` is required/);
1512915129
});
15130+
15131+
it('supports updateOne with update pipeline', async function() {
15132+
const schema = new Schema({ name: String, age: Number });
15133+
const Person = db.model('Person', schema);
15134+
15135+
const doc = new Person({ name: 'test' });
15136+
await doc.updateOne(
15137+
[
15138+
{
15139+
$set: {
15140+
age: {
15141+
$round: [
15142+
{ $add: ['age', 1] },
15143+
0
15144+
]
15145+
}
15146+
}
15147+
}
15148+
],
15149+
{ updatePipeline: true }
15150+
);
15151+
});
1513015152
});
1513115153

1513215154
describe('Check if instance function that is supplied in schema option is available', function() {

0 commit comments

Comments
 (0)