質問

I'm having problems inserting documents into a mongoLab instance.

I'm connecting to the instance using this command :

MongoClient client = new MongoClient(new MongoClientURI(uri));

with uri that look like this :

mongodb://heroku_app1234:random_password@ds029017.mongolab.com:29017/heroku_app1234

the user heroku_app1234 has the status readOnly to false

and inserting my document like this :

Jongo jongo = new Jongo(client.getDB("myDb"));
MongoCollection collection = jongo.getCollection("myCollection");
collection.save(someBean);
client.close();

and the server crash with this exception :

Caused by: com.mongodb.WriteConcernException: { "serverUsed" : "ds029017.mongolab.com:29017" , "err" : "not authorized for insert on myDb.myCollection" , "code" : 16544 , "n" : 0 , "lastOp" : { "$ts" : 0 , "$inc" : 0} , "connectionId" : 21382 , "ok" : 1.0} 
役に立ちましたか?

解決

It looks like you're connecting and authenticating to one database (heroku_app1234) but then switching to another (myDB). You're getting the error not authorized for insert on myDb.myCollection as a result.

When you grab the database to pass into the Jongo() constructor you should be sure to grab the same one as used in the URI. It looks like you're using Java. If so, this tweak to your code may work for you:

MongoClientUri uri = new MongoClientUri("mongodb://heroku_app1234:random_password@ds029017.mongolab.com:29017/heroku_app1234");
MongoClient client = new MongoClient(uri);
Jongo jongo = new Jongo(client.getDB(uri.getDatabase()));
MongoCollection collection = jongo.getCollection("myCollection");
collection.save(someBean);
client.close();

We have some basic connection examples in our Language Center, including one for Java that you can feel free to pull from.

// Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname
MongoClientURI uri  = new MongoClientURI("mongodb://user:pass@host:port/db"); 
MongoClient client = new MongoClient(uri);
DB db = client.getDB(uri.getDatabase());
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top