diff --git a/lib/model.js b/lib/model.js index 84eb3c7e937..5a09efac493 100644 --- a/lib/model.js +++ b/lib/model.js @@ -1394,6 +1394,14 @@ Model.createCollection = async function createCollection(options) { } } + const clusteredIndex = this && + this.schema && + this.schema.options && + this.schema.options.clusteredIndex; + if (clusteredIndex != null) { + options = Object.assign({ clusteredIndex: { ...clusteredIndex, unique: true } }, options); + } + try { await this.db.createCollection(this.$__collection.collectionName, options); } catch (err) { diff --git a/test/model.test.js b/test/model.test.js index de81227bf67..c6e0648c9a0 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -5122,6 +5122,37 @@ describe('Model', function() { assert.ok(collOptions.timeseries); }); + it('createCollection() respects clusteredIndex', async function() { + const version = await start.mongodVersion(); + if (version[0] < 6) { + this.skip(); + return; + } + + const schema = Schema({ name: String, timestamp: Date, metadata: Object }, { + clusteredIndex: { + key: { _id: 1 }, + name: 'clustered test' + }, + autoCreate: false, + autoIndex: false + }); + + const Test = db.model('Test', schema, 'Test'); + await Test.init(); + + await Test.collection.drop().catch(() => {}); + await Test.createCollection(); + + const collections = await Test.db.db.listCollections().toArray(); + const coll = collections.find(coll => coll.name === 'Test'); + assert.ok(coll); + assert.deepEqual(coll.options.clusteredIndex.key, { _id: 1 }); + assert.equal(coll.options.clusteredIndex.name, 'clustered test'); + + await Test.collection.drop().catch(() => {}); + }); + it('mongodb actually removes expired documents (gh-11229)', async function() { this.timeout(1000 * 80); // 80 seconds, see later comments on why const version = await start.mongodVersion();