Finding broken references

Wondering if anyone has found a simple method to identify broken references between collections using Velo code. Thanks in advance.

db

Hey Dave, hope you are talking about single-refs, because I never work with multi’s.
For single refs, “broken” could mean:

  1. the ref field is empty
  2. the ref field is not empty, but it point to a non-existing entry in another table

Solutions:
ad 1) just query the collection, iterate over every entry and check for !refFieldName
ad 2) try a query using an .include on the ref and, again, see if every row has some kind of field from referenced table that you would expect to be included in the query

Does that make sense?

Giri,

It does make sense. The use case is the one where the single ref points to record that no longer exists. Had not tried your method (I guess I may have been overthinking it), so will give that a whirl.

I have also tried to find a method that works with multi ref fields. Still a work in progress, but that is a bit more difficult, as multi refs return an array or object that has to be parsed to determine the broken reference. I have a “wish list” item out there to improve referential integrity, but I suspect that may be constrained by the limits of MongoDB as it is exposed to Velo. Thanks for the help.

So… your approach made sense, but does not work quite right. Here’s why: When using the .include on the single ref, the call will return the .include object if the single ref is valid. If the single ref is broken (not valid), then the .include only returns the string value of the invalid single ref. Javascript barfs, because strings are not objects.

So to figure out if there is broken reference, I used the .typeof method on the single ref field to determine if it is an object or a string. If it is a string, then the reference is broken. Simple, but not obvious.

Now if I can figure out multi refs…

Glad you figured it out.