Search code examples
node.jsmongodbmongooseschemaunique

Get fields set to unique in schema from Mongoose


I have a desire to check which fields in a schema are set to unique, similar to getting the indexes for a schema via MyCollection.collection.getIndexes(). Can this information be found somewhere on the schema object?


Solution

  • Try this:

    var schema = new mongoose.Schema({
      a: {
        type: String,
        unique: true
      },
      b: {
        type: String
      }
    });
    
    schema.tree.a.unique; // true
    schema.tree.b.unique; // undefined
    
    schema.path('a').options.unique; // true
    schema.path('b').options.unique; // undefined