@@ -1079,7 +1079,7 @@ Schema.setMethod(function getFieldNames() {
10791079 *
10801080 * @author Jelle De Loecker <jelle@elevenways.be>
10811081 * @since 0.2.0
1082- * @version 1.4.0
1082+ * @version 1.4.1
10831083 *
10841084 * @param {string|FieldType } _field_or_name Field name, or index name when using `fields` option
10851085 * @param {Object } options
@@ -1111,15 +1111,46 @@ Schema.setMethod(function addIndex(_field_or_name, _options) {
11111111 // When `fields` is provided, the first argument is the index name
11121112 options . name = _field_or_name ;
11131113
1114+ // Create the index entry
1115+ if ( this . indexes [ options . name ] == null ) {
1116+ this . indexes [ options . name ] = {
1117+ fields : { } ,
1118+ options : options
1119+ } ;
1120+ }
1121+
1122+ // Add all fields to the index
11141123 for ( let field_name of options . fields ) {
1115- this . addIndex ( field_name , {
1116- name : options . name ,
1117- unique : options . unique ,
1118- sparse : options . sparse ,
1119- order : options . order ,
1120- } ) ;
1124+ let field = this . getField ( field_name ) ;
1125+
1126+ if ( ! field ) {
1127+ throw new Error ( 'Could not find field "' + field_name + '" for compound index "' + options . name + '"' ) ;
1128+ }
1129+
1130+ let path = field . path ;
1131+ this . indexes [ options . name ] . fields [ path ] = options . order || 1 ;
1132+ this . index_fields [ path ] = options ;
11211133 }
11221134
1135+ // Now call ensureIndex once with the complete compound index
1136+ const that = this ;
1137+
1138+ that . getDatasource ( ) . done ( function gotDs ( err , datasource ) {
1139+ if ( err ) {
1140+ throw err ;
1141+ }
1142+
1143+ if ( datasource . supports ( 'ensure_index' ) === false ) {
1144+ return ;
1145+ }
1146+
1147+ datasource . ensureIndex ( that . model_class , that . indexes [ options . name ] , function ensuredIndex ( err , result ) {
1148+ if ( err ) {
1149+ alchemy . printLog ( 'error' , [ 'Error ensuring compound index' , options . name , 'in model' , that . model_name ] , { err : err } ) ;
1150+ }
1151+ } ) ;
1152+ } ) ;
1153+
11231154 return ;
11241155 }
11251156
0 commit comments