Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow adding descending indexes on schema #8896

Merged
merged 4 commits into from
May 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions lib/helpers/schema/getIndexes.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ module.exports = function getIndexes(schema) {
const indexTypes = schema.constructor.indexTypes;
const indexByName = new Map();

const collectIndexes = function(schema, prefix, baseSchema) {
collectIndexes(schema);
return indexes;

function collectIndexes(schema, prefix, baseSchema) {
// Ignore infinitely nested schemas, if we've already seen this schema
// along this path there must be a cycle
if (schemaStack.has(schema)) {
Expand Down Expand Up @@ -72,7 +75,8 @@ module.exports = function getIndexes(schema) {
field[prefix + key] = 'text';
delete options.text;
} else {
field[prefix + key] = 1;
const isDescendingIndex = Number(index) === -1;
field[prefix + key] = isDescendingIndex ? -1 : 1;
}

delete options.type;
Expand Down Expand Up @@ -107,10 +111,7 @@ module.exports = function getIndexes(schema) {
});
indexes = indexes.concat(schema._indexes);
}
};

collectIndexes(schema);
return indexes;
}

/*!
* Checks for indexes added to subdocs using Schema.index().
Expand Down
18 changes: 18 additions & 0 deletions test/model.indexes.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,24 @@ describe('model', function() {
});
});

it('creates descending indexes from schema definition(gh-8895)', function() {
return co(function*() {
const userSchema = new Schema({
name: { type: String, index: -1 },
address: { type: String, index: '-1' }
});

const User = db.model('User', userSchema);

yield User.init();

const indexes = yield User.collection.getIndexes();

assert.ok(indexes['name_-1']);
assert.ok(indexes['address_-1']);
});
});

describe('auto creation', function() {
it('can be disabled', function(done) {
const schema = new Schema({ name: { type: String, index: true } });
Expand Down