Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Collection modify() and remove() via findAndModify #45

Merged
merged 7 commits into from
Dec 30, 2023

Conversation

thekid
Copy link
Member

@thekid thekid commented Dec 30, 2023

This pull requests adds new methods to the Collection class:

  • modify() - much like upsert, with the difference that it also returns the modified document.
  • remove() - same as delete but returns the document as it existed before deletion

These methods are slower by nature because of the document being part of the response payload. If you're not interested in the modified / deleted documents, simply use upsert and delete.

Example

The following code becomes more concise:

  $statements= ['$set' => ['slug' => $slug, ...$entity]];
- $arguments= [
-   'query'  => ['slug' => $slug],
-   'update' => $statements,
-   'new'    => true,  // Return modified document
-   'upsert' => true,
- ];
- $value= $this->entries->run('findAndModify', $arguments)->value()['value'];
- $doc= $value ? new Document($value) : null; 
+ $doc= $this->entries->modify(['slug' => $slug], $statements, upsert: true)->document();

See also

@thekid thekid added the enhancement New feature or request label Dec 30, 2023
@thekid thekid changed the title Implement findAndModify command as Collection::modify() Implement Collection modify() and remove() via findAndModify Dec 30, 2023
@thekid thekid merged commit 5707dc0 into master Dec 30, 2023
20 checks passed
@thekid thekid deleted the feature/findAndModify branch December 30, 2023 13:19
@thekid
Copy link
Member Author

thekid commented Dec 30, 2023

@thekid
Copy link
Member Author

thekid commented Dec 30, 2023

Real-life example from https://github.com/thekid/crews:

   #[Put]
   public function describe(#[Value] User $user, ObjectId $group, #[Param] string $description) {
     // Shortened for brevity: Verify user is group owner
-    $result= $this->groups->run('findAndModify', [
-      'query'  => ['_id' => $group],
-      'update' => ['$set' => ['description' => $description]],
-      'new'    => true,  // Return modified document
-      'upsert' => false,
-    ]);
-    return View::named('group#description')->with($result->value()['value']);
+    $result= $this->groups->modify($group, ['$set' => ['description' => $description]]);
+    return View::named('group#description')->with($result->document());
   }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant