neu*_*ero 5 mongoose mongodb node.js promise async-await
我正在使用Jest为Node / Express / Mongo项目设置测试。我试图编写一个函数来清除集合,所以每个测试都以一个干净的状态开始:
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)
})
Run Code Online (Sandbox Code Playgroud)
再一次尝试,并保证:
const clearCollection = collectionName => {
const collection = mongoose.connection.collections[collectionName]
return collection.drop()
}
beforeEach(async () => {
await clearCollection('users')
})
Run Code Online (Sandbox Code Playgroud)
问题在于它们在工作和引发错误之间都交替出现。每次保存文件时,它要么完美运行,要么抛出错误,每次都交替出现。错误始终是以下之一:
MongoError: cannot perform operation: a background operation is currently running for collection auth_test.users
MongoError: ns not found
Run Code Online (Sandbox Code Playgroud)
通过clearCollection()在a内调用自身catch(),我可以使其在100%的时间内工作(无论如何受堆栈限制),但这感觉很不对劲:
const clearCollection = collectionName => {
const collection = mongoose.connection.collections[collectionName]
return collection.drop()
.catch(() => clearCollection(collectionName))
}
Run Code Online (Sandbox Code Playgroud)
我不知道为什么mongoose.connection.collections.<collection>.drop()随机抛出错误,但是有一种简单的方法可以删除 Mongoose 中的所有文档,它可以很好地在测试前重置集合:
beforeAll(async () => {
await User.remove({})
})
Run Code Online (Sandbox Code Playgroud)
每次都有效。