Skip to content

Commit 2a08814

Browse files
authoredNov 26, 2022
Merge pull request #12677 from rdeavilafloqast/gh-12676
Fixing diffIndexes to cleanly return error instead of resulting in ty…
2 parents ca7996b + 0096c3d commit 2a08814

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed
 

‎lib/model.js

+8
Original file line numberDiff line numberDiff line change
@@ -1427,6 +1427,14 @@ Model.diffIndexes = function diffIndexes(options, callback) {
14271427
return this.db.base._promiseOrCallback(callback, cb => {
14281428
cb = this.$wrapCallback(cb);
14291429
this.listIndexes((err, indexes) => {
1430+
if (err) {
1431+
// If the collection does not exist, it does not have indexes; safely proceed
1432+
if (err.codeName === 'NamespaceNotFound') {
1433+
indexes = [];
1434+
} else {
1435+
return cb(err, { toDrop, toCreate });
1436+
}
1437+
}
14301438
const schemaIndexes = this.schema.indexes();
14311439
// Iterate through the indexes created in mongodb and
14321440
// compare against the indexes in the schema.

‎test/model.indexes.test.js

+9
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,15 @@ describe('model', function() {
7070
});
7171
});
7272

73+
it('should have schema-defined indexes in toCreate when calling diffIndexes on model with no documents (gh-12676)', () => {
74+
const MySchema = new Schema({
75+
name: { type: String, index: true }
76+
});
77+
78+
const MyModel = db.model('my-model', MySchema); // This collection should not exist in DB; no documents
79+
return MyModel.diffIndexes().then((res) => assert.deepEqual(res.toCreate[0], { name: 1 }));
80+
});
81+
7382
it('of embedded documents', function(done) {
7483
const BlogPosts = new Schema({
7584
_id: { type: ObjectId, index: true },

0 commit comments

Comments
 (0)
Please sign in to comment.