title: Avoiding loops in a mongo db parent child tree
body: <p>I am looking at using a mongo db design similar to: <a href="https://docs.mongodb.com/manual/tutorial/model-tree-structures-with-parent-references/" rel="nofollow noreferrer">https://docs.mongodb.com/manual/tutorial/model-tree-structures-with-parent-references/</a></p>
  
  <p>What's the best practice for guaranteeing that we do not create loops in the document structure?</p>
  
  <p>i.e. A is parent of B, B is parent C, C is parent of A</p>
  
  <p>We have two ideas, one is to create a schema object so that we need to define that type B can have a parent of type A. This call can do the validation in a POST on a schema object. And successive creating of nodes with type B will just make the parent type A.</p>
  
  <p>The other idea is that in memory (relatively small DB of possibly a few thousand nodes), I do an in memory check via a search of the tree to make sure the new node that is added, doesn't form a loop in the tree.</p>
  
  <p>Am I misusing mongo? That's my real question, I guess. I am using this structure because it creates really nice and quick queries since I store individual nodes. However the concern for creating corrupt data is there. </p>