MongoUtility

The MongoUtility.js JavaScript library supports and demonstrates how to use the MongoDB Java driver and is available as a wrapper. Use this JavaScript library to make the process of using JavaScript easier. 

How to Use the MongoUtility JavaScript Library

Use the following process to work with the JavaScript library:

  1. Enable the MongoUtility.js JavaScript library.
  2. Configure the server properties as a JSON expression.
  3. Create a new instance of the JavaScript library.
  4. Create a connection to the server.

Enable the JavaScript Library

Go to Create, API Properties, Libraries, System libraries tab, select the Used checkbox for the MongoUtility.js system library, and save your changes.

Configure the Server Properties as a JSON Expression

Enter the following code snippet:

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

The server properties are configured.

Create a New Instance of the JavaScript Library

Create a new instance of the utility your JavaScript code and pass in the setup configuration by issuing the following command:

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

Create a Connection to the Server

Create a connection to the server (and optional security logon) by entering the following commands:

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 by entering the following commands:

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 by entering the following commands:

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. (The following libraries are required):

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("-------------");