Mongoose.connection.collections.collection.drop () throws error every time
I am setting up testing with Jest for a Node / Express / Mongo project. I tried to write a function to clean up collections, so every test starts from scratch:
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)
})
And one more try: promises:
const clearCollection = collectionName => {
const collection = mongoose.connection.collections[collectionName]
return collection.drop()
}
beforeEach(async () => {
await clearCollection('users')
})
The problem is they both alternate between work and error. Every time I save the file it either works fine or generates an error alternating each time. Errors are always either one of:
MongoError: cannot perform operation: a background operation is currently running for collection auth_test.users
MongoError: ns not found
I can get it to work 100% of the time (limited by the stack anyway) by creating a clearCollection()
call inside catch()
, but it seems so wrong:
const clearCollection = collectionName => {
const collection = mongoose.connection.collections[collectionName]
return collection.drop()
.catch(() => clearCollection(collectionName))
}
+3
source to share
1 answer