2016-02-14 38 views
1

每当我运行我的Mocha测试时,它都会在创建索引和不创建它之间交替。我认为它不会创建索引,因为测试可能在完成之前就已经运行了,但是因为它交替出现了这样的模式,我不认为是这种情况。我也认为这可能与我在每次测试开始时丢弃数据库有关,但这不应该以某种方式影响每一个测试。Mongoose索引在Mocha测试中没有创建一半时间

所关注的索引:

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(); 
     }); 
    }); 
}); 

任何想法是什么引起的?

+0

mongoose使用不同的'.ensureIndex()'(是仍然是调用)方法为数据库连接上定义的索引创建索引。在连接之后,你明确地调用底层驱动程序方法的'.dropDatabase()'。总之,当你吹走数据库时你还会期望什么?如果您期望“索引”保持原位,那么请在相关集合/模型上调用'.remove()'。这不会“删除”索引或集合(或实际上是数据库),而只是在插入新数据之前使内容无效。 –

+0

为什么每隔一段时间都会工作?如果在创建索引后删除索引,索引不应该出现吗? – user36322

+0

他们可能不会。你可以在你调用'.dropDatabase()'的时候显示一个可重现的情况,并且之后还有索引可用吗?无论如何,我相信这是“锅运气”,特别是如果索引创建被要求以“后台”模式运行。如果你想要一个坚实的行为,那么你最好自己编写索引创建阶段的脚本。猫鼬索引创建的“默认行为”实际上被认为是“开发便利性”,并且还建议在生产环境中关闭该选项。 –

回答

1

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

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(); 
      }); 
     }); 
    }); 
}); 
相关问题