Skip to content

Commit 9ee8c55

Browse files
author
WebFreak001
committed
Fix #2
1 parent fcbb559 commit 9ee8c55

File tree

1 file changed

+40
-3
lines changed

1 file changed

+40
-3
lines changed

source/mongoschema/package.d

+40-3
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import vibe.db.mongo.connection;
66
import std.datetime;
77
import std.traits;
88
import core.time;
9-
import std.typecons : tuple;
9+
import std.typecons : tuple, Nullable;
1010

1111
// Bson Attributes
1212

@@ -375,6 +375,14 @@ T fromSchemaBson(T)(Bson bson)
375375
return obj;
376376
}
377377

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+
378386
/// Mixin for functions for interacting with Mongo collections.
379387
mixin template MongoSchema()
380388
{
@@ -413,10 +421,18 @@ mixin template MongoSchema()
413421
return true;
414422
}
415423

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+
416432
/// Finds one element with the object id `id`
417433
static typeof(this) findById(BsonObjectID id)
418434
{
419-
return fromSchemaBson!(typeof(this))(_schema_collection_.findOne(Bson(["_id" : Bson(id)])));
435+
return fromSchemaBson!(typeof(this))(findOneOrThrow(Bson(["_id" : Bson(id)])));
420436
}
421437

422438
/// Finds one element with the hex id `id`
@@ -428,7 +444,28 @@ mixin template MongoSchema()
428444
/// Finds one element using a query.
429445
static typeof(this) findOne(T)(T query)
430446
{
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));
432469
}
433470

434471
/// Finds one or more elements using a query.

0 commit comments

Comments
 (0)