i think $document should not be allowed to be null. rather pass $fv resp. $fieldValue when you walk the references. you do have the documents in that place. otherwise behaviour could depend on which order documents and references are processed.