删除集合后恢复Mongoose上的索引

时间:2016-07-04 05:01:16

标签: mongoose

我在NodeJS应用程序中使用Mongoose ORM。在集成测试上,我编写了一个删除所有集合afterEach test的函数。

但现在存在一个问题,即在删除集合后不会恢复唯一约束索引。

此测试在隔离运行时有效,因为在测试运行之前未删除该集合。

it('should fail to save when identifier exists', function(done){
  newItem.identifier = existingItem.identifier;
  newItem.save(function (err, result) {
    should.exist(err);
    done(null);
  });
});

但是当它在整个测试套件中运行时,在每个测试之间使用这个帮助方法删除集合:

function deleteCollection(collection, done){
  var collections = _.keys(mongoose.connection.collections);
  async.forEach(collections, function (collectionName, next) {
    var collection = mongoose.connection.collections[collectionName];
    collection.drop(function (err) {
      if (err && err.message != 'ns not found') return next(err);
      next(null);
    })
 }, function(err, result){
  done(err, result);
  });
}

我直接检查了数据库,并且在运行之间删除了集合后,缺少标识符上的集合唯一索引。

有没有办法重新运行Mongoose模式,以便在每次测试之间重新创建索引?

1 个答案:

答案 0 :(得分:0)

您可以在每个模特上致电ensureIndexes,例如beforeEach

beforeEach(function(done) {
  var modelNames = _.keys(mongoose.models);
  async.forEach(modelNames, function (modelName, next) {
    mongoose.models[modelName].ensureIndexes(next);
  }, done);
});