Skip to content
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
9 changes: 9 additions & 0 deletions lib/field-collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@ var Collection = require('./collection');
* Container for a list of Fields.
*/
var FieldCollection = Collection.extend({
comparator: function (a, b) {
// make sure _id is always at top, even in presence of uppercase fields
var aId = a.getId();
var bId = b.getId();
if (aId === '_id') return -1;
if (bId === '_id') return 1;
// otherwise sort case-insensitively
return (aId.toLowerCase() < bId.toLowerCase()) ? -1 : 1;
},
model: function(attrs, options) {
return new attrs.klass(attrs, options);
}
Expand Down
26 changes: 26 additions & 0 deletions test/field-order.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
var getSchema = require('../');
var assert = require('assert');
var debug = require('debug')('mongodb-schema:test:field-order');

describe('order of fields', function () {
it('should have _id fields always at top, even with uppercase fields', function(done) {
var docs = [ {FOO: 1, _id: 1, BAR: 1, zoo: 1} ];
getSchema('field.order', docs, function (err, schema) {
assert.ifError(err);
assert.deepEqual(schema.fields.map(function (field) {
return field.getId();
}), ['_id', 'BAR', 'FOO', 'zoo']);
done();
});
});
it('should sort in case-insensitive manner', function (done) {
var docs = [ {cb: 1, Ca: 1, cC: 1, a:1, b: 1} ];
getSchema('field.order', docs, function (err, schema) {
assert.ifError(err);
assert.deepEqual(schema.fields.map(function (field) {
return field.getId();
}), ['a', 'b', 'Ca', 'cb', 'cC']);
done();
});
});
});