Run javascript file from MongoDB C# driver - javascript

I'm trying to use Variety, a custom tool/script for MongoDB (2.6) in the C# driver for MongoDB.
I was able to run it successfully through the commandline, but I'm unsure how to run it's equivalent in the C# driver.
bin\mongo db --eval "var collection = 'coll', limit = 20" bin\variety.js
1. Javascript location
I ran the command above when the javascript was located in bin\ next to mongo.exe. Following the manual I went on and placed the file in \data\db\scripts. However I also read about the system.js file.
Is placing it in \data\db\scripts the right way? Or do I have to register it in system.js?
2. Running the script
This example on running a stored procedure in MongoDB shows how to execute a method with two arguments. However the Variety tool uses some sort of context variables which I need to provide in order for it to execute (collection and limit for instance). In the commandline they are provided as string which is evaluated before the name of the script file.
What is the equivalent of the commandline execution? I can't get the result2 variable right. How do I pass an entire script file instead of a function name?
MongoClient client = new MongoClient("mongodb://0.0.0.0/db");
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase("db");
BsonValue result1 = db.Eval("var collection = 'coll', limit = 20");
BsonValue result2 = db.Eval(result1.AsBsonJavaScript.Code, "variety.js");

Related

How to write the argument of a function in the terminal with node js

I'm using this code to connect to mailchimp API, get a list of members and put all their email adresses in an array:
var mailchimpMarketing = require("#mailchimp/mailchimp_marketing");
mailchimpMarketing.setConfig({
apiKey: "MY API KEY",
server: "MY SERVER",
});
async function getArrayEmailMembersFromMailchimpListID(listID){
const response = await mailchimpMarketing.lists.getListMembersInfo(listID);
const emailsMailchimp = response.members.map(member => member.email_address);
console.log(emailsMailchimp)
return emailsMailchimp;
}
getArrayEmailMembersFromMailchimpListID("MY LIST ID")
My problem is that I want to write the list ID "MY LIST ID" in my terminal and not in my code when I'm starting the script. Something like that:
$node test.js MyListID
Instead of
$node test.js
But I don't know how to do it.
I think it's possible with process.argv or minimist but I don't understand how they work. Can someone explain it to me or is their any other possibility ?
From the Node-JS v8.x documentation:
The process.argv property returns an array containing the command line
arguments passed when the Node.js process was launched. The first
element will be process.execPath. See process.argv0 if access to the
original value of argv[0] is needed. The second element will be the
path to the JavaScript file being executed. The remaining elements
will be any additional command line arguments.
So in your case you can simply do:
getArrayEmailMembersFromMailchimpListID(process.argv[2])
Of course you should add some error-handling for this to make it more robust.

How to get data from back end side, to use it in the browser side?

I am new to programming, and I heard that some guys on this website are quite angry, but please don't be. I am creating one web app, that has a web page and also makes som ecalculations and works with database (NeDB). I have an index.js
const selects = document.getElementsByClassName("sel");
const arr = ["Yura", "Nairi", "Mher", "Hayko"];
for (let el in selects) {
for (let key in arr) {
selects[el].innerHTML += `<option>${arr[key]}</option>`;
}
}
I have a function which fills the select elements with data from an array.
In other file named: getData.js:
var Datastore = require("nedb");
var users = new Datastore({ filename: "players" });
users.loadDatabase();
const names = [];
users.find({}, function (err, doc) {
for (let key in doc) {
names.push(doc[key].name);
}
});
I have some code that gets data from db and puts it in array. And I need that data to use in the index.js mentioned above, but the problem is that I don't know how to tranfer the data from getData.js to index.js. I have tried module.exports but it is not working, the browser console says that it can't recognize require keyword, I also can't get data directly in index.js because the browse can't recognize the code related to database.
You need to provide a server, which is connected to the Database.
Browser -> Server -> DB
Browser -> Server: Server provides endpoints where the Browser(Client) can fetch data from. https://expressjs.com/en/starter/hello-world.html
Server -> DB: gets the Data out of the Database and can do whatever it want with it. In your case the Data should get provided to the Client.
TODOs
Step 1: set up a server. For example with express.js (google it)
Step 2: learn how to fetch Data from the Browser(Client) AJAX GET are the keywords to google.
Step 3: setup a Database connection from you Server and get your data
Step 4: Do whatever you want with your data.
At first I thought it is a simple method, but them I researched a little bit and realized that I didn't have enough information about how it really works. Now I solved the problem, using promises and templete engine ejs. Thank you all for your time. I appreciate your help)

Protractor Test with oracle Db

I requirement to test the DB alongside my angular app. The scenario is such that I do something on UI and see if the value persists in the DB(Oracle)
For this purpose, I installed node oracle DB package and was able to run a simple SELECT statement using the command "Node filename.js". The config and the select statement were present in the filename.js
Next, I tried to include the same steps in my step definition. The first step of my test case navigates to the application home page and the next step is to run a simple select statement. I have no asserts as I wanted to first get a basic query working
Here is my step def
let oracledb = require('oracledb');
let dbConfig = require('../configs/dbConfig');
Given(/^I run a random select query$/, function() {
let sql2 = "Select * from tablename Where columname = 8888901";
oracledb.getConnection(dbConfig).then(function(connection) {
//return console.log('Connected to database');
return connection.execute(sql2).then(function(result, err) {
return console.log(result.rows.toString());
});
});
});
When the test runs the browser opens and the home page is loaded and then the test is passed. I don't think the 2nd step is even run as the query result is not printed in the console.
Could someone please point me in the right direction. Can protractor work with OracleDB? have I written the test correct? I have so many questions regarding this and there is not a single online sample for a protractor test with oracledb. Any inputs here will be helpful, thanks

how to read terminal input in node.js?

I want to do some local node test before push the code to server.
how can I read terminal input as a input for my js script?
readline or something
I think there is no need to use third party library, if you just want to get command line params.
You can use process.argv property of process node core object.
just use process.argv & you are good to go.It returns an array in which by default there is 2 element, at 0 index Node execution directory & at 1 index working directory, so cmd line params start from 2nd index.
So in nutshell, you can access cmd line params using process.argv[2] onwards.
For commandline app you can use nicl. you can make call to your chat module or websocket or whatever based on your logic.
var nicl = require("nicl");
function main() {
nicl.printLine("Hello, what is your name?");
var name = nicl.readLine();
//call to websocket or any chat module
nicl.printLine("Great to meet you, " + name + "!");
process.exit(0);
}
nicl.run(main);

redis.exceptions.ResponseError: MOVED error in redis set operation

I have created a Redis cluster with 30 instances (15 masters/ 15 nodes). With python code i connected to these instances, i found the masters and then i wanted to add some keys to them.
def settomasters(port, host):
r = redis.Redis( host=host, port=port )
r.set("key"+port,"value")
Error:
redis.exceptions.ResponseError: MOVED 12539 127.0.0.1:30012
If i try to set key from redis-cli -c -p portofmyinstance sometimes i get a redirection message that tells where the keys stored.
I know that in case of get requests for example, a smart client is needed in order to redirect the requests to the correct node (the node that holds the key) otherwise a moved error occurs. Is it the same situation? I need to catch the redis.exceptions.ResponseError and try to set again?
while True:
try:
r.set("key","value")
break
except:
print "error"
pass
My first try was above code but without solution. The set operation never succeeds.
On the other hand below code in javascript does not throw an error and i cannot figure the reason:
var redis = require('redis-stream'),
client = new redis(30001, '127.0.0.1');
// Open stream
var stream = client.stream();
// Example of setting 200 records
for(var record = 0; record <200; record++) {
var command = ['set', 'qwerty' + record, 'QWERTYUIOP'];
stream.redis.write( redis.parse(command) );
}
stream.on('close', function () {
console.log('Completed!');
});
// Close the stream after batch insert
stream.end();
Any help will be appreciated, thanks.
with a redis cluster you can use the normal redis client only if you "find for the certain key the slot that belongs and then the slots that each master serves. With this information i can set keys to the correct node without moved redirection errors." as #Antonis said. Otherwise you need http://redis-py-cluster.readthedocs.io/en/master/

Categories