@@ -6,7 +6,7 @@ import vibe.db.mongo.connection;
6
6
import std.datetime ;
7
7
import std.traits ;
8
8
import core.time ;
9
- import std.typecons : tuple;
9
+ import std.typecons : tuple, Nullable ;
10
10
11
11
// Bson Attributes
12
12
@@ -375,6 +375,14 @@ T fromSchemaBson(T)(Bson bson)
375
375
return obj;
376
376
}
377
377
378
+ class DocumentNotFoundException : Exception
379
+ {
380
+ this (string msg, string file = __FILE__ , size_t line = __LINE__ ) pure nothrow @nogc @safe
381
+ {
382
+ super (msg, file, line);
383
+ }
384
+ }
385
+
378
386
// / Mixin for functions for interacting with Mongo collections.
379
387
mixin template MongoSchema()
380
388
{
@@ -413,10 +421,18 @@ mixin template MongoSchema()
413
421
return true ;
414
422
}
415
423
424
+ static auto findOneOrThrow (T)(T query)
425
+ {
426
+ Bson found = _schema_collection_.findOne(query);
427
+ if (found.isNull)
428
+ throw new DocumentNotFoundException(" Could not find one " ~ typeof (this ).stringof);
429
+ return found;
430
+ }
431
+
416
432
// / Finds one element with the object id `id`
417
433
static typeof (this ) findById (BsonObjectID id)
418
434
{
419
- return fromSchemaBson! (typeof (this ))(_schema_collection_.findOne (Bson([" _id" : Bson(id)])));
435
+ return fromSchemaBson! (typeof (this ))(findOneOrThrow (Bson([" _id" : Bson(id)])));
420
436
}
421
437
422
438
// / Finds one element with the hex id `id`
@@ -428,7 +444,28 @@ mixin template MongoSchema()
428
444
// / Finds one element using a query.
429
445
static typeof (this ) findOne (T)(T query)
430
446
{
431
- return fromSchemaBson! (typeof (this ))(_schema_collection_.findOne(query));
447
+ return fromSchemaBson! (typeof (this ))(findOneOrThrow(query));
448
+ }
449
+
450
+ static Nullable! (typeof (this )) tryFindById (BsonObjectID id)
451
+ {
452
+ Bson found = _schema_collection_.findOne(Bson([" _id" : Bson(id)]));
453
+ if (found.isNull)
454
+ return Nullable! (typeof (this )).init;
455
+ return Nullable! (typeof (this ))(fromSchemaBson! (typeof (this ))(found));
456
+ }
457
+
458
+ static Nullable! (typeof (this )) tryFindById (string id)
459
+ {
460
+ return tryFindById (BsonObjectID.fromString(id));
461
+ }
462
+
463
+ static Nullable! (typeof (this )) tryFindOne (T)(T query)
464
+ {
465
+ Bson found = _schema_collection_.findOne(query);
466
+ if (found.isNull)
467
+ return Nullable! (typeof (this )).init;
468
+ return Nullable! (typeof (this ))(fromSchemaBson! (typeof (this ))(found));
432
469
}
433
470
434
471
// / Finds one or more elements using a query.
0 commit comments