title: How to get the connected objects within a collection in an array in Mongoose MongoDb NodeJS
body: <p>I am new to NodeJS and I am using NodeJS Framework HapiJs. I have parent-child schema of a Model "Elements" in which parent and child belongs to the same collection. The schema is similar to following:</p>
  
  <pre><code>var mschema = new Schema({
      autoIncrementId: { type: Number,unique: true,index:true,sparse:true},
      elementName: {
          type: String,
          required: true
      },
      elementCanvasId: {
          type: String,
          required: true
      },
      parentId: {
          type: Schema.Types.ObjectId,
          required: false,
          ref: "Elements",
      },
      parentCanvasId: {
          type: String,
          required: false
      },
  });
  
  var modules = Mongoose.model('Elements', mschema);
  </code></pre>
  
  <p>here <code>elementCanvasId</code> is generated at client side. And <code>parentCanvasId</code> is a reference to <code>elementCanvasId</code> of the parent element. Also its not necessary that every element will have a parent. Now based on <code>elementCanvasId</code> of element I wanna fetch all the elements that comes under hierarchy(i.e all its children elements and then children's subchildren and then their's subchildren and so on.) of that element in a Single Dimensional Array. I cannot use <code>Schema.Types.ObjectId</code> for this purspose as I only have to use <code>elementCanvasId</code> which is generated at client's side only. So, can someone help me out to get it done. Any kind of help is hugely appreciated. Thanks in advance.</p>