Heroku MongoHQ add-on and PyMongo -- OperationFailure: database error: unauthorized

flask, heroku, mongodb, mongohq, python

Solution

You likely need to run the `authenticate` command against the DB directly after you connect.

Try something like this:

db.authenticate([USER], [PASSWORD])

If that doesn't work, feel free to email support@mongohq.com and we can help you out with your specific DB.

Problem

I'm having trouble with the MongoHQ Heroku addon. Locally my app works and the os variable is present and well-formed on Heroku. However, when I attempt to access the db it throws an error: `OperationFailure: database error: unauthorized db:my_database ns:my_database.cars lock type:0 client:128.62.187.133`. If I try to hard-code the connection string from MongoHQ and run locally, I get the same error. My app is below: ``` import os import datetime from flask import Flask from flask import g from flask import jsonify from flask import json from flask import request from flask import url_for from flask import redirect from flask import render_template from flask import make_response import pymongo from pymongo import Connection from bson import BSON from bson import json_util app = Flask(__name__) def mongo_conn(): # Format: MONGOHQ_URL: mongodb://<user>:<pass>@<base_url>:<port>/<url_path> if os.environ.get('MONGOHQ_URL'): return Connection(os.environ['MONGOHQ_URL']) else: return Connection() @app.route('/', methods=['GET', 'POST']) def hello(): # Get your DB connection = mongo_conn() db = connection.my_database # Create an object car = {"brand": "Ford", "model": "Mustang", "date": datetime.datetime.utcnow()} # Get your collection cars = db.cars # crashes # Insert it cars.insert(car) ... ``` Edit: MongoHQ support helped me. Problem was that I was calling my database `my_database` instead of the actual DB name given to me by the MongoHQ addon. E.g., `db = connection.app52314314`. That change fixed it.

Original source