Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions lib/helpers/setDefaultsOnInsert.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

const modifiedPaths = require('./common').modifiedPaths;
const get = require('./get');

/**
* Applies defaults to update and findOneAndUpdate operations.
Expand Down Expand Up @@ -95,7 +95,9 @@ module.exports = function(filter, schema, castedDoc, options) {
if (!isModified(modified, path) && typeof def !== 'undefined') {
castedDoc = castedDoc || {};
castedDoc.$setOnInsert = castedDoc.$setOnInsert || {};
castedDoc.$setOnInsert[path] = def;
if (get(castedDoc, path) == null) {
castedDoc.$setOnInsert[path] = def;
}
updatedValues[path] = def;
}
}
Expand Down
31 changes: 30 additions & 1 deletion test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6805,7 +6805,7 @@ describe('Model', function() {
});
});

it('Model#bulkWrite(...) does not throw an error when provided an empty array (gh-9131)', function() {
it('Model.bulkWrite(...) does not throw an error when provided an empty array (gh-9131)', function() {
return co(function*() {
const userSchema = new Schema();
const User = db.model('User', userSchema);
Expand Down Expand Up @@ -6839,4 +6839,33 @@ describe('Model', function() {
);
});
});

it('Model.bulkWrite(...) does not throw an error with upsert:true, setDefaultsOnInsert: true (gh-9157)', function() {
return co(function*() {
const userSchema = new Schema(
{
friends: [String],
age: { type: Number, default: 25 }
},
{ timestamps: true }
);
const User = db.model('User', userSchema);

yield User.bulkWrite([
{
updateOne: {
filter: { },
update: { friends: ['Sam'] },
upsert: true,
setDefaultsOnInsert: true
}
}
]);

const user = yield User.findOne().sort({ _id: -1 });

assert.equal(user.age, 25);
assert.deepEqual(user.friends, ['Sam']);
});
});
});