title: Indexing array of references using mongodb multikey indexing method in mongoose
body: <p>My schema has an array of ObjectIds which are refs to another schema. What i want is to index this array entry using multikey indexing method of mongodb. 
  So that given an <strong>ObjectId</strong> of some document in the <strong>ProductCat</strong> Collection, i can list all the documents in my current collection which has the given <strong>ObjectId</strong> in the <strong>_pro_cat</strong> field. </p>
  
  <p>I am confused about the exact way in which i should declare the field, in mongoose schema declaration, Here is what i am trying:</p>
  
  <pre><code>_pro_cat: { type: [mongoose.Schema.Types.ObjectId], ref: 'ProductCat', index: true }
  
  _pro_cat: [{ type: mongoose.Schema.Types.ObjectId, ref: 'ProductCat', index: true }]
  </code></pre>
  
  <p>The name of this collection is Seller. I am making the relation, by using the reference in the schema and the actual field value is an array, each of type ObjectId, which will be the ObjectIds of the documents in the other Collection (ProductCat in this case). If i index this field i.e.. _pro_cat, then given an ObjectId of a document in ProductCat Collection, i would be able to find all the documents in the Seller collection which has given ObjectId in its array field _pro_cat.</p>
  
  <p>I think i may have to call a separate index function. But i thought that this is a field level indexing so it may not be needed.</p>
  
  <p>I suspect the later is only for sub-docs and not for refs. Would greatly appreciate, if anyone could shed some light on it. Thanks.</p>
  
  <p><strong>Side Question: [RE-SOLVED]</strong>
  In the mongodb documentation, it says that multikey indexing is automatic. <a href="http://docs.mongodb.org/manual/core/index-multikey/" rel="nofollow noreferrer">multikey indexing</a>. Does this mean that if that field is indexed, using the above methods, then mongo will recognize that the field is an array and use multikey indexing. OR does it mean that all the fields which are of array type will get indexed, without the need to explicitly telling it to index.</p>
  
  <p>Thanks a lot.</p>
  
  <p><a href="https://stackoverflow.com/questions/10568281/mongoose-using-populate-on-an-array-of-objectid/">related</a></p>