MongoUtility

The MongoUtility.js is a JavaScript library that is available as a wrapper to support and demonstrate using the MongoDB Java Driver.

Step 1. - Enable the MongoUtility.js script by selecting (used) in the Project/Library section.

 


Step 2. - Configure the server properties as a JSON expression

var configSetup = {
   serverName  : 'localhost',
   serverPort  : '27017' ,
   databaseName: 'Audit'
};

Step 3- Create a new instance of the Utility in your JavaScript code and pass in the setup configuration from step 2.

var mongoClient = MongoUtilityCreate();
mongoClient.configure(configSetup);

Step 4 - Create a connection to the server (and optional security logon)


var payload = {
    username: "demo",
    password: "Password1"
};

var DB = mongoClient.createClientConnection(payload);


Query Function: Execute a query on a specific collection and return an array of results

var collectionName = "MyCollection';
var query = {name: 'foo'};
var array =runMongoQuery(collectionName, query, {}, {}, 10, 0) ;//collectionName, query, columns, sort, limit, offset

Insert Function: Insert a JSON collection into Mongo Collection

var payload= logicContext.rowToJSON(row);
var result = mongoClient.mongoInsert("audit","EspressoAudit", payload);

Close the connection

mongoClient.close();

The sample programs are attached to demonstrate how to wrap JavaScript around existing Java. (You will need to following libraries)

java -cp target/classes:target/lib/mongo-java-driver-2.11.2.jar:target/lib/commons-logging-1.1.1.jar:target/lib/httpclient-4.2.5.jar:target/lib/httpcore-4.2.4.jar:target/lib/rhino-1.7R4.jar org.mozilla.javascript.tools.shell.Main test.js




function MongoUtilityCreate() {



var result = {};
var errorMsg = null;
var clientConnection = null;
var DB = null;
var configSetup = {
    serverName : '',
    serverPort : '',
    databaseName : ''
};


// FUNCTION this call must be made first to pass in the required SQL
// configuration values

result.configure = function configure(myConfig) {
configSetup.serverName = myConfig.serverName || '';
configSetup.serverPort = myConfig.serverPort || '';
configSetup.databaseName = myConfig.databaseName || '';
};

// local function to take username and password to create a server
// connection
result.createClientConnection = function createClientConnection(payload) {
    var port = '27017';
    if (configSetup.serverPort.length > 1) {
        port = configSetup.serverPort;
    }

    var user = payload.username;
    var pw = payload.password;
    clientConnection = new com.mongodb.MongoClient(configSetup.serverName, port);
    DB = clientConnection.getDB(configSetup.databaseName);
    if (user != null && pw != null) {
    var ans = DB.authenticate(user, (new java.lang.String(pw)).toCharArray());
        if (ans === false) {
            return {
            error : 'unable to authenticate'
            };
        }
    }
return DB;
};


// FUNCTION RunMongoQuery - returns result of a simple query on a collection
result.runMongoQuery = function runMongoQuery(collectionName, query, columns, sort, limit, offset) {
var result = [];
var count = 0;
var queryObj = null;

try {
var collection = DB.getCollection(collectionName);
if (query) {
    queryObj = new com.mongodb.BasicDBObject(query);
}
var rst = collection.find(queryObj);// ,columns).sort(sort).limit(limit).skip(offset);
    while (rst.hasNext()) {
        result.push(JSON.parse(rst.next()));
        count = count + 1;
    }
} catch (e) {
    errorMsg = e.message;
}

var queryResponse = {
    errorMessage : errorMsg,
    response : result,
    count: count
};
return queryResponse;
};


result.mongoInsert = function mongoInsert(fieldName, collectionName,collValue) {
var response = "";
try {
    var collection = DB.getCollection(collectionName);
    collection.insert(new com.mongodb.BasicDBObject(fieldName,collValue));
    response = "success";
} catch (e) {
errorMsg = e.message;
    response = errorMsg;
}
return {
    response : response
    };
};

result.close = function close(){
try{
    clientConnection.close();
    DB.close();
} catch (e) {}
};

return result;
}
Test.js

// 1. load the class

load("MongoUtility.js");

// 2. configuration needed for testing

var configSetup = {

   serverName  : 'localhost',

   serverPort  : '27017' ,

   databaseName: 'Audit'

};

// 3.this is how the server creates the security object

var mongoClient = MongoUtilityCreate();

mongoClient.configure(configSetup);

var payload = {

    username: "Tyler",

    password: "password1"

};


var DB = mongoClient.createClientConnection(payload);


out.println("------------- testing mongo query for EspressoAudit");

var query = {"name": "Bill's Auto Body"};

var result = mongoClient.runMongoQuery("EspressoAudit", {}, {}, {}, 10, 0);

out.println(JSON.stringify(result, null, 2));

out.println("-------------");

ċ
MongoUtilityProject.PNG
(31k)
Val Huber,
Feb 16, 2016, 2:28 PM
ċ
test.js
(1k)
Val Huber,
Feb 16, 2016, 2:28 PM
Comments