Open thekid opened 7 months ago
Currently, the pattern is first() ?? throw:
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()?
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?
all()
optional()
See also https://stackoverflow.com/questions/31171451/getting-a-single-object-from-mongodb-in-c-sharp
Called get() here: https://github.com/mono-js/mongodb-utils
get()
Currently, the pattern is
first() ?? throw
:Can we create a utility method for this like
single()
?Should there also be an
all()
method to select all, and anoptional()
to select zero or one?