Middleware that logs errors to MongoDB