Copy a database using mongo driver - mongodb

I have the following code:
mongoServer.CopyDatabase(mongoDatabaseName, partitionName.Replace("__", string.Empty));
mongoServer.DropDatabase(mongoDatabaseName);
I obtain the following exception "NotImplementedException - The method or operation is not implemented."
How is it possible? I've wronged something? How can I copy my database?

The exception is correct as the CopyDatabase method isn't implemented. See the JIRA ticket for the history of the issue.
Instead, you need to directly invoke the 'copydb' command via a call to RunCommand on the admin database like is described in this answer. So something like:
var adminDB = Server.GetDatabase("admin");
var command = new CommandDocument(new List<BsonElement> {
new BsonElement("copydb", 1),
new BsonElement("fromhost", "localhost"),
new BsonElement("fromdb", mongoDatabaseName),
new BsonElement("todb", partitionName.Replace("__", string.Empty))
});
var result = adminDB.RunCommand(command);

Related

"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.

Calling XSJS file in SAPUI5 for writng data on HANA

I'm trying to create a service to write data from a SAPUI5 frontend to HANA tables.
As far as I checked, I believe this is not possible via OData Services. So I've found another way, sing an XSJS file with a SQL INSERT statement.
Now, my problem is using this in UI5. As with OData, I would use something like oModel.create but now I think this doesn't work like that.
Those anyone has a clue?
Thanks!
Eva
UPDATE:
After using the first answer, I tried to create an entry in a HANA Table, but I'm getting a 500 error. Here's the code of the xsjs file:
var data = '', conn = $.db.getConnection(), pstmt;
if($.request.body){
data = $.request.parameters.get("firstName");
}
var conn = $.db.getConnection();
var pstmt = conn.prepareStatement( 'INSERT INTO "Z003HB1N"."T_TEST" (FIRSTNAME) VALUES(?)' );
pstmt.setString(1,data);
pstmt.execute();
pstmt.close();
conn.commit();
conn.close();
doResponse(200,'');
$.response.contentType = 'text/plain';
$.response.setBody('Upload ok');
$.response.status = 200;
Any clue what might be wrong?
You can simply use .ajax calls to call your new oData service on HANA and use parameters to hand over the desired values to your .xsjs service.
Example:
var query = "firstName=Sherlock&lastName=Holmes"
jQuery.ajax({
url : "url/to/your/Service.xsjs?" + query,
success : function(response) {
// will be called once the xsjs file sends a response
console.log(response);
},
error : function(e) {
// will be called in case of any errors:
console.log(e);
}
});
On HANA you can access the provided parameters in your service like this:
var firstName = $.request.parameters.get("firstName");
var lastName = $.request.parameters.get("lastName");

Meteor: Unique MongoDB URL for different users

I'm very keen to utilize Meteor as the framework for my next project. However, there is a requirement to keep customer data separated into different MongoDB instances for users from different customers.
I have read on this thread that it could be as simple as using this:
var d = new MongoInternals.RemoteCollectionDriver("<mongo url>");
C = new Mongo.Collection("<collection name>", { _driver: d });
However, I was dished this error on my server/server.js. I'm using meteor 0.9.2.2
with meteor-platform 1.1.0.
Exception from sub Ep9DL57K7F2H2hTBz Error: A method named '/documents/insert' is already defined
at packages/ddp/livedata_server.js:1439
at Function._.each._.forEach (packages/underscore/underscore.js:113)
at _.extend.methods (packages/ddp/livedata_server.js:1437)
at Mongo.Collection._defineMutationMethods (packages/mongo/collection.js:888)
at new Mongo.Collection (packages/mongo/collection.js:208)
at Function.Documents.getCollectionByMongoUrl (app/server/models/documents.js:9:30)
at null._handler (app/server/server.js:12:20)
at maybeAuditArgumentChecks (packages/ddp/livedata_server.js:1594)
at _.extend._runHandler (packages/ddp/livedata_server.js:943)
at packages/ddp/livedata_server.js:737
Can anyone be so kind as to enlighten me whether or not I have made a mistake somewhere?
Thanks.
Br,
Ethan
Edit: This is my server.js
Meteor.publish('userDocuments', function () {
// Get company data store's mongo URL here. Simulate by matching domain of user's email.
var user = Meteor.users.findOne({ _id: this.userId });
if (!user || !user.emails) return;
var email = user.emails[0].address;
var mongoUrl = (email.indexOf('#gmail.com') >= 0) ?
'mongodb://localhost:3001/company-a-db' :
'mongodb://localhost:3001/company-b-db';
// Return documents
return Documents.getCollectionByMongoUrl(mongoUrl).find();
});
and this is the server side model.js
Documents = function () { };
var documentCollections = { };
Documents.getCollectionByMongoUrl = function (url) {
if (!(url in documentCollections)) {
var driver = new MongoInternals.RemoteCollectionDriver(url);
documentCollections[url] = new Meteor.Collection("documents", { _driver: driver });
}
return documentCollections[url];
};
Observation: The first attempt to new a Meteor.Collection works fine. I can continue to use that collection multiple times. But when I log out and login as another user from another company (in this example by using an email that is not from #gmail.com), the error above is thrown.
Downloaded meteor's source codes and peeked into mongo package. There is a way to hack around having to declare different collection names on the mongodb server based on Hubert's suggestion.
In the server side model.js, I've made these adaptation:
Documents.getCollectionByMongoUrl = function (userId, url) {
if (!(userId in documentCollections)) {
var driver = new MongoInternals.RemoteCollectionDriver(url);
documentCollections[userId] = new Meteor.Collection("documents" + userId, { _driver: driver });
documentCollections[userId]._connection = driver.open("documents", documentCollections[userId]._connection);
}
return documentCollections[userId];
};
Super hack job here. Be careful when using this!!!!
I believe Meteor distinguish its collections internally by the name you pass to them as the first argument, so when you create the "documents" collection the second time, it tries to override the structure. Hence the error when trying to create the /documents/insert method the second time.
To work around this, you could apply a suffix to your collection name. So instead of:
new Meteor.Collection('documents', { _driver: driver });
you should try:
new Meteor.Collection('documents_' + userId, { _driver: driver })

Mongodb authentication using MongoCredential

I have a grails application in which Im using db.authenticate for a login page but I understand this method has been deprecated and therefore I would like to upgrade my application to using the MongoCredential object for authentication. However, unlike the db.authenticate which nicely returns a boolean to get authentication done, the MongoCredential doesn't return a boolean so how can I go about accomplishing the code replacement with minimal headache. Ideally, I'd like to derive some kind of a boolean to tell me if authentication was achieved. Thanks for your patience. Im a newbie with Mongodb.
This is part of the code I need to replace which currently makes use of the deprecated method "authenticate":
MongoClient mongoClient = new MongoClient("localhost", 27017)
DB db = mongoClient.getDB("twcdb");
def userName = params.username
def passWord = params.password
//deprecated method being used in the line below.
boolean auth = db.authenticate(userName, passWord.toCharArray())
if (auth) {
userloggedin = params.username
render(contentType: 'text/json') {
[success: true, url: createLink(controller: 'admin', action: 'loggedin')]
}
}
else {
render(contentType: 'text/json') {
["success": false, "message": 'Login or Password is incorrect.']
}
Edit: I know that the answer must lie in testing a property of the MongoClient object somehow to see if it contains a valid authenticated connection but I am still stuck on how to do this. Given I knowingly feed the MongoClient constructor with a bogus MongoCredential, it still creates an object that isn't null. I was betting on the null test but no joy. So, how do I replace the deprecated db.authenticate?

GetDatabaseName:

I have a problem when retrieving the names of existing databases:
<code>
var connectionString = "mongodb://user:pw#localhost/admin";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var lst = server.GetDatabaseNames();
lst.Dump(); -- this is in Linqpad
</code>
Linqpad reports:
<code>
Command 'listDatabases' failed: need to login (response: { "errmsg" : "need to login", "ok" : 0.0 })
The same error happens when omitting the database name in the connection string.
The same error happens when using in my c# application.
Could you please explain how to get that list?
Well, in the meantime a had a look at the documentation (which I should have done before, sorry) and found out that I had to use this function with a parameter providing the admin credentials.
OK. BUT the error message is confusing and should be something like: You must provide the admin credentials..............
You can try,
const string legalConnectionString = "mongodb://localhost/?safe=true";
var productionMongoDatabase = MongoServer.Create(legalConnectionString ).GetDatabase(productionDb, new MongoCredentials("admin", "1111111", true));