Skip to content

Commit

Permalink
fix(model): skip createCollection() in syncIndexes() if autoCreate: f…
Browse files Browse the repository at this point in the history
…alse
  • Loading branch information
vkarpov15 committed Jan 3, 2025
1 parent ddd6f83 commit 4d4bd00
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
20 changes: 11 additions & 9 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -1246,19 +1246,21 @@ Model.syncIndexes = async function syncIndexes(options) {
throw new MongooseError('Model.syncIndexes() no longer accepts a callback');
}

const model = this;
const autoCreate = options?.autoCreate ?? this.schema.options?.autoCreate ?? this.db.config.autoCreate ?? true;

try {
await model.createCollection();
} catch (err) {
if (err != null && (err.name !== 'MongoServerError' || err.code !== 48)) {
throw err;
if (autoCreate) {
try {
await this.createCollection();
} catch (err) {
if (err != null && (err.name !== 'MongoServerError' || err.code !== 48)) {
throw err;
}
}
}

const diffIndexesResult = await model.diffIndexes();
const dropped = await model.cleanIndexes({ ...options, toDrop: diffIndexesResult.toDrop });
await model.createIndexes({ ...options, toCreate: diffIndexesResult.toCreate });
const diffIndexesResult = await this.diffIndexes();
const dropped = await this.cleanIndexes({ ...options, toDrop: diffIndexesResult.toDrop });
await this.createIndexes({ ...options, toCreate: diffIndexesResult.toCreate });

return dropped;
};
Expand Down
22 changes: 22 additions & 0 deletions test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4885,6 +4885,28 @@ describe('Model', function() {
assert.deepStrictEqual(indexes.map(index => index.name), ['_id_', 'name_1']);
});

it('avoids creating collection if autoCreate: false', async() => {
const collectionName = generateRandomCollectionName();
const userSchema = new Schema(
{ name: { type: String, index: true } },
{ autoIndex: false, autoCreate: false, collation: { locale: 'en_US', strength: 2 } }
);
const User = db.model('User', userSchema, collectionName);

// Act
await User.syncIndexes();

// Assert
const indexes = await User.listIndexes();
assert.deepStrictEqual(indexes.map(index => index.name), ['_id_', 'name_1']);

const collections = await User.db.listCollections();
const collection = collections.find(c => c.name === collectionName);
assert.ok(collection);
// Collation was not applied because autoCreate was false, so Mongoose did not send `createCollection()`
assert.ok(!collection.options.collation);
});

it('drops indexes that are not present in schema', async() => {
// Arrange
const collectionName = generateRandomCollectionName();
Expand Down

0 comments on commit 4d4bd00

Please sign in to comment.