Skip to content

Commit 8a8ff91

Browse files
authored
Merge pull request #9160 from AbdelrahmanHafez/gh-9157
fix(model): fix conflicting $setOnInsert default values with `update` values in bulkWrite
2 parents 58f3376 + b364a8d commit 8a8ff91

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

lib/helpers/setDefaultsOnInsert.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
'use strict';
2-
32
const modifiedPaths = require('./common').modifiedPaths;
3+
const get = require('./get');
44

55
/**
66
* Applies defaults to update and findOneAndUpdate operations.
@@ -95,7 +95,9 @@ module.exports = function(filter, schema, castedDoc, options) {
9595
if (!isModified(modified, path) && typeof def !== 'undefined') {
9696
castedDoc = castedDoc || {};
9797
castedDoc.$setOnInsert = castedDoc.$setOnInsert || {};
98-
castedDoc.$setOnInsert[path] = def;
98+
if (get(castedDoc, path) == null) {
99+
castedDoc.$setOnInsert[path] = def;
100+
}
99101
updatedValues[path] = def;
100102
}
101103
}

test/model.test.js

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6805,7 +6805,7 @@ describe('Model', function() {
68056805
});
68066806
});
68076807

6808-
it('Model#bulkWrite(...) does not throw an error when provided an empty array (gh-9131)', function() {
6808+
it('Model.bulkWrite(...) does not throw an error when provided an empty array (gh-9131)', function() {
68096809
return co(function*() {
68106810
const userSchema = new Schema();
68116811
const User = db.model('User', userSchema);
@@ -6839,4 +6839,33 @@ describe('Model', function() {
68396839
);
68406840
});
68416841
});
6842+
6843+
it('Model.bulkWrite(...) does not throw an error with upsert:true, setDefaultsOnInsert: true (gh-9157)', function() {
6844+
return co(function*() {
6845+
const userSchema = new Schema(
6846+
{
6847+
friends: [String],
6848+
age: { type: Number, default: 25 }
6849+
},
6850+
{ timestamps: true }
6851+
);
6852+
const User = db.model('User', userSchema);
6853+
6854+
yield User.bulkWrite([
6855+
{
6856+
updateOne: {
6857+
filter: { },
6858+
update: { friends: ['Sam'] },
6859+
upsert: true,
6860+
setDefaultsOnInsert: true
6861+
}
6862+
}
6863+
]);
6864+
6865+
const user = yield User.findOne().sort({ _id: -1 });
6866+
6867+
assert.equal(user.age, 25);
6868+
assert.deepEqual(user.friends, ['Sam']);
6869+
});
6870+
});
68426871
});

0 commit comments

Comments
 (0)