Skip to content

Commit 90f9e55

Browse files
authored
Merge pull request #14621 from priceshape-development/fix/add-shard-key-to-bulk-write-operations
fix: ensure buildBulkWriteOperations target shard if shardKey is set
2 parents 53362c3 + c2352f3 commit 90f9e55

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

lib/model.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3956,6 +3956,17 @@ Model.buildBulkWriteOperations = function buildBulkWriteOperations(documents, op
39563956

39573957
_applyCustomWhere(document, where);
39583958

3959+
// If shard key is set, add shard keys to _filter_ condition to right shard is targeted
3960+
const shardKey = this.schema.options.shardKey;
3961+
if (shardKey) {
3962+
const paths = Object.keys(shardKey);
3963+
const len = paths.length;
3964+
3965+
for (let i = 0; i < len; ++i) {
3966+
where[paths[i]] = shardKey[paths[i]];
3967+
}
3968+
}
3969+
39593970
// Set the discriminator key, so bulk write casting knows which
39603971
// schema to use re: gh-13907
39613972
if (document[discriminatorKey] != null && !(discriminatorKey in where)) {

test/model.test.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6331,14 +6331,14 @@ describe('Model', function() {
63316331

63326332
const userSchema = new Schema({
63336333
name: { type: String }
6334-
});
6334+
}, { shardKey: { a: 1 } });
63356335

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

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

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

63556355
assert.deepEqual(

0 commit comments

Comments
 (0)