Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose.connection.collections.collection.drop() throws error every other time

I am setting up testing using Jest for an Node/Express/Mongo project. I have tried to write a function to clear collections so each test starts with a clean slate:

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 another try, with promises:

const clearCollection = collectionName => {
  const collection = mongoose.connection.collections[collectionName]
  return collection.drop()
}

beforeEach(async () => {
  await clearCollection('users')
})

The problem is that it they both alternate between working and throwing an error. Every time I save the file, it either works perfectly, or throws an error, alternating each time. The 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 making clearCollection() call itself inside a catch(), but this feels so wrong:

const clearCollection = collectionName => {
  const collection = mongoose.connection.collections[collectionName]
  return collection.drop()
    .catch(() => clearCollection(collectionName))
}
like image 753
neurozero Avatar asked Mar 23 '17 06:03

neurozero


1 Answers

I don't know why mongoose.connection.collections.<collection>.drop() randomly throws errors, but there is a simple way to remove all the documents in Mongoose, which works just fine for resetting the collection before tests:

beforeAll(async () => {
  await User.remove({})
})

Works every time.

like image 58
neurozero Avatar answered Oct 16 '22 08:10

neurozero