Factor out maybe_add_docid function