Ertai87
Ertai87

Reputation: 1316

MongoDB (or Morphia) conditional reference

I have a MongoDB collection C whose schema contains a manual reference to another collection D, and I'm using Morphia in Java to manage both C and D. D has a boolean field b in its schema, and I would like to validate my reference against b (i.e. when a new document c is written to collection C, if its reference points to some entity d in the D collection, then if the boolean value b of d is false, then MongoDB should throw an error).

To describe a bit more concretely, let's say you have 2 standard POJOs to represent the MongoDB collection schemas:

class C {
    @Id
    public String id;

    @Reference
    public D target; 
}

class D {
    @Id
    public String id;

    public boolean b;
}

Based on this schema, a sample insert operation would look like this (JSON):

{
    "target" : { "id": "MY_FANCY_ID" }
    //There is a record with id = "MY_FANCY_ID" in collection D
}

When inserting a new C with a non-null target (D), I would like to check if target.b is false, and if it is, then throw a database error.

1) Is there a way to do this natively in MongoDB?
2) If not 1), then is there a way to manage this in Morphia (without some extremely obtuse and verbose hack)?

Thanks!

Upvotes: 0

Views: 245

Answers (1)

evanchooly
evanchooly

Reputation: 6243

Natively to MongoDB, you're out of luck. With Morphia you could use something like @PerPersist to do the extra query to check for that boolean value. It would mean an extra query every time you save a C unless you engineer some shortcut to only do the query on an initial insert. Checking if the ID is null might help here.

Upvotes: 1

Related Questions