mongoose.connection.collections.collection.drop()每隔一次都会抛出错误
我正在使用Jest为Node / Express / Mongo项目设置testing。 我试图写一个函数来清除集合,所以每个testing都以一个干净的平板开始:
const clearCollection = (collectionName, done) => { const collection = mongoose.connection.collections[collectionName] collection.drop(err => { if (err) throw new Error(err) else done() ) } beforeEach(done => { clearCollection('users', done) })
另一个尝试,承诺:
const clearCollection = collectionName => { const collection = mongoose.connection.collections[collectionName] return collection.drop() } beforeEach(async () => { await clearCollection('users') })
问题是它们在工作和抛出错误之间交替。 每次我保存文件时,它都可以正常工作,或者每次都会发生错误。 错误总是或者是以下之一:
MongoError: cannot perform operation: a background operation is currently running for collection auth_test.users MongoError: ns not found
我可以通过在clearCollection()
调用自己的clearCollection()
来100%的工作(不pipe怎样都限制堆栈catch()
,但是这种感觉是错误的:
const clearCollection = collectionName => { const collection = mongoose.connection.collections[collectionName] return collection.drop() .catch(() => clearCollection(collectionName)) }
我不知道为什么mongoose.connection.collections.<collection>.drop()
随机抛出错误,但是有一个简单的方法可以移除Mongoose中的所有文件,在testing之前重新设置集合就可以了。
beforeAll(async () => { await User.remove({}) })
每次工作。