在Mochatesting中,Mongoose索引不会创build一半时间

每当我运行我的摩卡testing,它交替创build索引,而不是创build它。 我认为这不是创build索引的原因,因为testing可能在完成之前就已经运行了,但是因为它交替出现了这样的模式,我不认为是这种情况。 我也认为这可能与我在每次testing开始时丢弃数据库有关,但是不应该以某种方式影响每一个testing。

有问题的索引:

submissionSchema.index({ studentID: 1, assignmentID: 1 }, { unique: true }); 

要删除数据库的代码:

 before(function(done){ mongoose.createConnection(require(__dirname + '/../app/config').mongoURL, function(err){ if (err) throw err; mongoose.connection.db.dropDatabase(function(err){ if (err) throw err; done(); }); }); }); 

任何想法是什么造成这个?

Blake Sevens是对的。 为了解决这个问题,我在删除数据库之后重build了索引。

 before(function(done){ mongoose.createConnection(require(__dirname + '/../app/config').mongoURL, function(err){ if (err) throw err; mongoose.connection.db.dropDatabase(function(err){ if (err) throw err; var rebuildIndexes = [] var models = Object.keys(mongoose.connections[0].base.modelSchemas); models.forEach(function(model){ rebuildIndexes.push(function(cb){ mongoose.model(model, mongoose.connections[0].base.modelSchemas[model]).ensureIndexes(function(err){ return cb(err); }) }); }); async.parallel(rebuildIndexes, function(err) { if (err) throw err; console.log('Dumped database and restored indexes'); done(); }); }); }); });