Skip to content

Commit

Permalink
Addresses Automattic#12435
Browse files Browse the repository at this point in the history
  • Loading branch information
lpizzinidev committed Sep 16, 2022
1 parent 586c86f commit 62173de
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/document.js
Expand Up @@ -1735,7 +1735,7 @@ Document.prototype.$inc = function $inc(path, val) {
this.invalidate(path, new MongooseError.CastError('number', val, path, err));
}

const currentValue = this.$__getValue(path);
const currentValue = this.$__getValue(path) || 0;

this.$__setValue(path, currentValue + val);

Expand Down
12 changes: 12 additions & 0 deletions test/document.test.js
Expand Up @@ -11864,6 +11864,18 @@ describe('document', function() {
assert.strictEqual(doc.sub.propertyB, 'foo');
assert.strictEqual(called, 1);
});

it('If the field does not exist, $inc should create it and set is value to the specified one (gh-12435)', async function() {
const schema = new mongoose.Schema({
count: Number
});
const Model = db.model('IncTest', schema);
const doc = new Model({ });
await doc.save();
doc.$inc('count', 1);
await doc.save();
assert.strictEqual(doc.count, 1);
});
});

describe('Check if instance function that is supplied in schema option is availabe', function() {
Expand Down

0 comments on commit 62173de

Please sign in to comment.