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

Select a single document #46

Open
thekid opened this issue Mar 22, 2024 · 2 comments
Open

Select a single document #46

thekid opened this issue Mar 22, 2024 · 2 comments
Labels
question Further information is requested

Comments

@thekid
Copy link
Member

thekid commented Mar 22, 2024

Currently, the pattern is first() ?? throw:

// Using find()
$post= $posts->find(new ObjectId($id))->first() ?? throw new Error(404);

// Using aggregate()
$cursor= $posts->aggregate([
  ['$match' => ['_id' => new ObjectId($id), 'state' => null, 'published' => ['$ne' => null]]],
  ['$lookup' => [
    'from'         => 'network',
    'localField'   => 'published.by.id',
    'foreignField' => '_id',
    'as'           => 'publisher',
  ]],
  ['$addFields' => ['publisher' => ['$arrayElemAt' => ['$publisher', 0]]]],
]);
$post= $cursor->first() ?? throw new Error(404);

Can we create a utility method for this like single()?

// Passing string|ObjectId will find() by _id
$post= $posts->single(new ObjectId($id));

// Passing an array will use aggregate()
$post= $posts->single([
  ['$match' => ['_id' => new ObjectId($id), 'state' => null, 'published' => ['$ne' => null]]],
  ['$lookup' => [
    'from'         => 'network',
    'localField'   => 'published.by.id',
    'foreignField' => '_id',
    'as'           => 'publisher',
  ]],
  ['$addFields' => ['publisher' => ['$arrayElemAt' => ['$publisher', 0]]]],
]);

Should there also be an all() method to select all, and an optional() to select zero or one?

@thekid
Copy link
Member Author

thekid commented Mar 22, 2024

@thekid thekid added the question Further information is requested label Mar 22, 2024
@thekid
Copy link
Member Author

thekid commented Mar 22, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant