Skip to content

Commit

Permalink
Merge pull request #14621 from priceshape-development/fix/add-shard-k…
Browse files Browse the repository at this point in the history
…ey-to-bulk-write-operations

fix: ensure buildBulkWriteOperations target shard if shardKey is set
  • Loading branch information
vkarpov15 authored May 30, 2024
2 parents 53362c3 + c2352f3 commit 90f9e55
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
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

Check failure on line 3959 in lib/model.js

View workflow job for this annotation

GitHub Actions / Lint JS-Files

Trailing spaces not allowed
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

0 comments on commit 90f9e55

Please sign in to comment.