Skip to content

Commit

Permalink
fix(shell-api): map fields to projection in findAndModify MONGO…
Browse files Browse the repository at this point in the history
  • Loading branch information
addaleax authored Jul 29, 2024
1 parent 1570f12 commit 3bf0025
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/shell-api/src/collection.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1798,11 +1798,12 @@ describe('Collection', function () {
...options,
});

const { fields: projection, ...expectedOptions } = options;
expect(serviceProvider.findOneAndDelete).to.have.been.calledWith(
collection._database._name,
collection._name,
{ query: 1 },
{ ...options, sort: { sort: 1 } }
{ ...expectedOptions, sort: { sort: 1 }, projection }
);
});
});
Expand Down
11 changes: 11 additions & 0 deletions packages/shell-api/src/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -482,8 +482,19 @@ export default class Collection extends ShellApiWithMongoClass {
FindAndModifyMethodShellOptions,
'query' | 'update'
> = { ...options };
if (
reducedOptions.projection !== undefined &&
reducedOptions.fields !== undefined
) {
throw new MongoshInvalidInputError(
'Cannot specify both .fields and .projection for findAndModify()',
CommonErrors.InvalidArgument
);
}
reducedOptions.projection ??= reducedOptions.fields;
delete (reducedOptions as any).query;
delete (reducedOptions as any).update;
delete (reducedOptions as any).fields;
if (options.remove) {
return this.findOneAndDelete(options.query, reducedOptions);
}
Expand Down
1 change: 1 addition & 0 deletions packages/shell-api/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -783,6 +783,7 @@ export type FindAndModifyMethodShellOptions = {
remove?: boolean;
new?: boolean;
fields?: Document;
projection?: Document;
upsert?: boolean;
bypassDocumentValidation?: boolean;
writeConcern?: Document;
Expand Down
18 changes: 18 additions & 0 deletions packages/shell-api/src/integration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1097,6 +1097,24 @@ describe('Shell API (integration)', function () {
});
});

it('projects according to `fields`', async function () {
const result = await collection.findAndModify({
query: { doc: 4 },
new: true,
update: { doc: 4, asdf: true },
upsert: true,
fields: { asdf: 1, _id: 1 },
});
expect(Object.keys(result!)).to.deep.equal(['_id', 'asdf']);
expect(result!._id.constructor.name).to.equal('ObjectId');
expect(result!.asdf).to.equal(true);

expect(await findAllWithoutId(dbName, collectionName)).to.deep.include({
doc: 4,
asdf: true,
});
});

context('on server 4.2+', function () {
skipIfServerVersion(testServer, '< 4.2');
it('allows update pipelines', async function () {
Expand Down

0 comments on commit 3bf0025

Please sign in to comment.