Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

Indexing arbitrary user defined fields

I have an application which allows users to build their own forms/data models, and then query the data. Therefore I’d like to be able to index arbitrary user defined fields so that the querying is performant. I’ve structured my schema like this (using mongoose) but would like to know if there is a better way?

Each TemplateFieldSchema instance represents a user defined field which can either be a string, num, array of num, array of string, or array of references.

var TemplateFieldSchema = new Schema({
  topicId: {
    type: Schema.Types.ObjectId,
    ref: 'Topic'
  },
  // arbitrary form data
  str: { // string
    type: String
  },
  num: { // number
    type: Number
  },
  arrNum: { type: Array, "default": [] },
  arrStr: { type: Array, "default": [] },
  arrRef: [{
    displayName: {
      type: String,
      required: true
    },
    slug: {
      type: String,
      required: true
    },
    id: {
      type: Schema.Types.ObjectId,
      required: true
    }
  }]
});

TemplateFieldSchema.index({ str: 1 });
TemplateFieldSchema.index({ num: 1 });
TemplateFieldSchema.index({ arrNum: 1 });
TemplateFieldSchema.index({ arrStr: 1 });
TemplateFieldSchema.index({ 'arrRef.displayName': 1 });