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
11 changes: 11 additions & 0 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -3956,6 +3956,17 @@ Model.buildBulkWriteOperations = function buildBulkWriteOperations(documents, op

_applyCustomWhere(document, where);

// If shard key is set, add shard keys to _filter_ condition to right shard is targeted
const shardKey = this.schema.options.shardKey;
if (shardKey) {
const paths = Object.keys(shardKey);
const len = paths.length;

for (let i = 0; i < len; ++i) {
where[paths[i]] = shardKey[paths[i]];
}
}

// Set the discriminator key, so bulk write casting knows which
// schema to use re: gh-13907
if (document[discriminatorKey] != null && !(discriminatorKey in where)) {
Expand Down
10 changes: 5 additions & 5 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6331,14 +6331,14 @@ describe('Model', function() {

const userSchema = new Schema({
name: { type: String }
});
}, { shardKey: { a: 1 } });

const User = db.model('User', userSchema);

const users = [
new User({ name: 'Hafez1_gh-9673-1' }),
new User({ name: 'Hafez2_gh-9673-1' }),
new User({ name: 'I am the third name' })
new User({ name: 'Hafez1_gh-9673-1', a: 1 }),
new User({ name: 'Hafez2_gh-9673-1', a: 2 }),
new User({ name: 'I am the third name', a: 3 })
];

await users[2].save();
Expand All @@ -6349,7 +6349,7 @@ describe('Model', function() {
const desiredWriteOperations = [
{ insertOne: { document: users[0] } },
{ insertOne: { document: users[1] } },
{ updateOne: { filter: { _id: users[2]._id }, update: { $set: { name: 'I am the updated third name' } } } }
{ updateOne: { filter: { _id: users[2]._id, a: 1 }, update: { $set: { name: 'I am the updated third name' } } } }
];

assert.deepEqual(
Expand Down