Unable to connecto to mongoDB - mongodb

Trying to connect to mongoDB using MongoLab AddOn, I get the following error:
{ "$err" : "not authorized for query on myAppDB.Users", "code" : 13 }
when I run the following code:
private string connectionString = "mongodb://appharbor_93126661-e8b7-4986-958c-74e4ed8401e6:qj0boq192osh10rXXXXXXXX#ds027521.mongolab.com:27521/appharbor_93126661-e8b7-4986-958c-74e4ed8401e6";
private string dbName = "myAppDB";
private string userCollectionName = "Users";
private MongoCollection<User> GetUsersCollection()
{
MongoUrl url = new MongoUrl(connectionString);
MongoClient client = new MongoClient(url);
mongoServer = client.GetServer();
MongoDatabase database = mongoServer.GetDatabase(dbName);
MongoCollection<User> userCollection = database.GetCollection<User>(userCollectionName);
return userCollection;
}
I tried to connect from shell running the command:
mongo ds027521.mongolab.com:27521/appharbor_93126661-e8b7-4986-958c-74e4ed8401e6 -u appharbor_93126661-e8b7-4986-958c-74e4ed8401e6 -p qj0boq192osh10rXXXXXXXX
but also haven't managed to connect.
If anyone encountered similar issue or knows what is causing the problem I would be very thankful for any suggestion in prder to solve the problem.

Related

how to keep data when testing insert to mongodb collection with spring inside docker?

i have following test in spring boot 2.7.7 with mongodb as a database sevices
// UserController.java
#GetMapping(value = "admin", produces = MediaType.APPLICATION_JSON_VALUE)
public String getAdmin () {
JSONObject report = new JSONObject();
String dataAdmin = userRepo.findByUsername("admin");
if(dataAdmin == null) {
User myadmin = new User();
myadmin.setUsername("admin");
myadmin.setFirstname("admin");
myadmin.setLastname("admin");
myadmin.setEmail("admin#admin");
myadmin.setRole("admin");
userRepo.save(myadmin);
report.put("message", "admin generated");
} else {
report.put("message", "admin only generated once");
}
return report.toString();
}
// AppTests.java
#Test
#DisplayName("generate admin")
void isertAdmin() throws IOException {
userRepo.deleteAll();
URL url = new URL("http://"+ addrHost +":8080/users/admin");
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
String encoding = conn.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding);
MatcherAssert.assertThat(body, CoreMatchers.containsString("admin generated"));
}
#Test
#DisplayName("generate failed")
void isertAdminTwice() throws IOException {
URL url = new URL("http://"+ addrHost +":8080/users/admin");
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
String encoding = conn.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding);
MatcherAssert.assertThat(body, CoreMatchers.containsString("admin only generated once"));
}
# docker-compose.yml
db:
container_name: database
image: mongo
restart: always
environment:
MONGO_INITDB_DATABASE: mydb
first testing is to generate new record data admin. I need to make sure there's no any previous document that contains the same record, so i decided to clean the collection before generate admin data when visiting users/admin.
the secound testing is almost similar with the first testing, but it doesnt clean the collection, so its designed to generate error report because the admin record already exist.
Above testing is running as expected when i run the program outside docker. But, when i run inside the docker, the second test failed because the data has been filled from my first test is not exist. In second test display error with actual result equals to first test.

How to connect Mongolab with MongoDb.Driver

i'm testing mongolab with .netCore using MongoDb.Driver.
I have this connection string
mongodb://<dbuser>:<dbpassword>#mymongolaburl:46367/somedatabase
And i'm connecting this way
var connectionString = #"mongodb://<dbuser>:<dbpassword>#mymongolaburl:46367/somedatabase";
var databaseName = "somedatabase";
var client = new MongoClient(connectionString);
if (client != null)
{
_database = client.GetDatabase(databaseName);
_database.GetCollection<User>("User").InsertOne(new User {Name="Luke Skywalker" });
}
It is not working 'cause it says the database name is invalid, if i use the connection string without the database name
mongodb://<dbuser>:<dbpassword>#mymongolaburl:46367
I get a timeout execption.
I Already connected to database using Robo 3T.
Thanks in advance.
After one day i found how to do that in this link
The The solution is to specify which is database in the connection string
mongodb://<dbuser>:<dbpassword>#mymongolaburl:46367/?authSource=somedatabase
Thank you!

"Not authorized on ___ to execute command" with mLab + MongoDB ^3.0

Connects without a hitch, but on insert() throws me this error.
var MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
var url = 'mongodb://____:____#ds125565.mlab.com:25565/heroku_w268n9pj';
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
db = client.db('temp');
console.log("connected!");
const collection = db.collection('temp');
collection.insert([{
something: please
}
});
I saw some other answers regarding mLab accounts and credentials, but I just created a new admin account for this. Frustrating because it was working previously with v2.3.
When attempting to connect to an mlab database, you have to correctly specify the client. It's located at the end of your connection string, just after the final forward slash.
mlab_url = "mongodb://db_user_name:db_password#ds139725.mlab.com:39725/heroku_sd1fp182?retryWrites=false"
client = MongoClient(url)
db = client["heroku_sd1fp182"]
collection = db["coinHack"]
You may also get the error:
This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.
Just add "?retryWrites=false" to your connection string, as shown above.

How to get OObjectDatabaseTx from ConnectionPool?

According OrientDB official doc, I should create Connection Pool with Object API with following code.
// OPEN THE DATABASE
OObjectDatabaseTx db= OObjectDatabasePool.global().acquire("remote:localhost/petshop", "admin", "admin");
However, I found that OObjectDatabasePool class has been deprecated and suggested to use com.orientechnologies.orient.core.db.OPartitionedDatabasePool instead.
But in that way, how can I get OObjectDatabaseTx object? That is because OPartitionedDatabasePool.acquire() can only return ODatabaseDocumentTx object.
Hope there are someone knows how to resolve it.
Thanks
With this code you can get "object to connect to" and then make queries etc.
GET DOCUMENT DB
String remote = "remote:localhost/";
String nameDB = "domain";
String url = remote + nameDB;
OPartitionedDatabasePool pool = new OPartitionedDatabasePool(url, "admin", "admin");
ODatabaseDocumentTx db = pool.acquire();
//use example
List<ODocument> resultset = db.query(new OSQLSynchQuery<Object>("select from ORole"));
for(ODocument doc:resultset) {
System.out.println(doc);
}
db.close();
GET OBJECT DB
String remote = "remote:localhost/";
String nameDB = "TestPartitioned2";
String url = remote + nameDB;
OServerAdmin serverAdmin = new OServerAdmin(url).connect("root", "root");
serverAdmin.createDatabase(nameDB, "object", "plocal");
System.out.println(" Database '"+nameDB +"' created!..");
OPartitionedDatabasePool pool = new OPartitionedDatabasePool(url, "admin", "admin");
//object
OObjectDatabaseTx db = new OObjectDatabaseTx(pool.acquire());
db.getEntityManager().registerEntityClass(Person.class);
Person personA = db.newInstance(Person.class);
personA.setName("tennantA");
db.save(personA);
db.close();

How can I authenticate any database with given username and password in Mongo Java Driver 2.13.0?

Previously I could use db.authenticate(String username, char[] password) method. With 2.13.0, how can I achieve this?
There is no replacement for db.authenticate(). The driver will use the credentials provided and make sure the connections are authenticated as they are created.
Based on this mongodb-user discussion the Java Driver team is open to discussions on what the real need for the db.authenticate(...) method.
Use
import com.mongodb.MongoCredential;
MongoCredential mongoCred =
MongoCredential.createMongoCRCredential(String username, String
dbName, char[] password);
and create mongoclient using mongocredentials
com.mongodb.MongoClient.MongoClient(List seeds, List
credentialsList, MongoClientOptions options)
We can have user-password based authentication for databases, in that case we need to provide authorization credentials like below for new version.
MongoCredential journaldevAuth = MongoCredential.createPlainCredential("pankaj", "journaldev", "pankaj123".toCharArray());
MongoCredential testAuth = MongoCredential.createPlainCredential("pankaj", "test", "pankaj123".toCharArray());
List<MongoCredential> auths = new ArrayList<MongoCredential>();
auths.add(journaldevAuth);
auths.add(testAuth);
ServerAddress serverAddress = new ServerAddress("localhost", 27017);
MongoClient mongo = new MongoClient(serverAddress, auths);
If you are using older versions, you need to provide authentication details after getting the DB object like below
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("journaldev");
boolean auth = db.authenticate("pankaj", "pankaj123".toCharArray());