Skip to content

Commit

Permalink
Merge pull request Automattic#2607 from LearnBoost/Automatticgh-2322
Browse files Browse the repository at this point in the history
Support indexes for schemas that are embedded multiple times
  • Loading branch information
vkarpov15 committed Jan 21, 2015
2 parents 5046e86 + af431ba commit ea22e0e
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 9 deletions.
21 changes: 12 additions & 9 deletions lib/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -729,17 +729,16 @@ Object.defineProperty(Schema, 'indexTypes', {
Schema.prototype.indexes = function () {
'use strict';

var indexes = []
, seenSchemas = []
collectIndexes(this);
return indexes;
var indexes = [];
var seenPrefix = {};

function collectIndexes (schema, prefix) {
if (~seenSchemas.indexOf(schema)) return;
seenSchemas.push(schema);
var collectIndexes = function(schema, prefix) {
if (seenPrefix[prefix]) {
return;
}
seenPrefix[prefix] = true;

prefix = prefix || '';

var key, path, index, field, isObject, options, type;
var keys = Object.keys(schema.paths);

Expand Down Expand Up @@ -784,7 +783,11 @@ Schema.prototype.indexes = function () {
});
indexes = indexes.concat(schema._indexes);
}
}

};

collectIndexes(this);
return indexes;

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

it('of multiple embedded documents with same schema', function(done) {
var BlogPosts = new Schema({
_id: { type: ObjectId, index: true },
title: { type: String, index: true },
desc: String
});

var User = new Schema({
name: { type: String, index: true },
blogposts: [BlogPosts],
featured: [BlogPosts]
});

var db = start();
var UserModel = db.model('DeepIndexedModel', User, 'gh-2322');
var assertions = 0;

UserModel.on('index', function () {
UserModel.collection.getIndexes(function (err, indexes) {
assert.ifError(err);

for (var i in indexes) {
indexes[i].forEach(function(index){
if (index[0] === 'name') {
++assertions;
}
if (index[0] === 'blogposts._id') {
++assertions;
}
if (index[0] === 'blogposts.title') {
++assertions;
}
if (index[0] === 'featured._id') {
++assertions;
}
if (index[0] === 'featured.title') {
++assertions;
}
});
}

db.close();
assert.equal(5, assertions);
done();
});
});
});

it('compound: on embedded docs', function(done){
var BlogPosts = new Schema({
title : String
Expand Down

0 comments on commit ea22e0e

Please sign in to comment.