Synchronous monk mongodb query in nodejs - node.js

I am working with monk mongodb query in my nodejs application, when I execute the query I get the response asynchronously in a callback mechanism.
I want to wait for the query to execute and use the result.
The code
var mycoll = db.get('collection_name');
mycoll.find({"key":123},function(e,docs){
result=docs[0].arr[n]
});
Here arr is the array of numbers in a document, n is changing constantly thus asynchronous way gives wrong answer.
Can someone modify the code and guide me through.

Related

How to find multiple mongo db objects at once in node js

i am trying to run a search , it is working fine with findOne and recieving data but when i use find it just return some headers and prototypes like this
response i am getting
code
let data = await client
.db("Movies")
.collection("movies")
.find();
console.log(data);
please tell me where i am going wrong
Based on documentation
The toArray() method returns an array that contains all the documents from a cursor. The method iterates completely the cursor, loading all the documents into RAM and exhausting the cursor.
so just try
let data = await client
.db("Movies")
.collection("movies")
.find({}).toArray();
console.log(data);

How do you return a MySQL query result from a node REST API

The MySQL JavaScript api is asynchronous.
If I try to write the filling REST Endpoint it fails as the call to MySQL is asynchronous.
#endpoint
String getSometing(){
RetVal = MySQL.asynchApiQuery(“someSql”)
return RetVal;
}
It will fail as RetVal will not be populated when the function returns.
I’ve spoken to a number of people who rave about JavaScripts asynchronous capabilities yet they have been unable to solve this simple synchronous problem
I’m hoping for a simple answer but so far all I’ve got is observable,promise, subscribe, continuation all of which cannot return the query as a promise simply creates a new thread that cannot be associated with the invoked of the REST api.
Any answer to this should return RetVal and not simply print it.
Look forward to a simple answer.
It's asynchronous but it has something named "callback functions". You can use them to decide what's going to happen with data after a mysql query
Example:
db.query("sqlquery",(err,data)=>{console.log(data)})

Can I execute a raw MongoDB query in node-mongodb-native driver?

FYI - I know how to use the MongoDB driver and know this is not how one would use it in a web app, but this is not for a web app. My aim is to emulate the MongoDB shell in NodeJS
I'm writing a DB GUI and would like to execute a raw MongoDB query, eg db.tableName.find({ col: 'value' }). Can I achieve this using the native MongoDB driver? I'm using v2.2, which is current the latest version.
If not, how can I achieve this in NodeJS?
Note: The question has changed - see the updates below.
Original answer:
Yes.
Instead of:
db.tableName.find({ col: 'value' })
You use it as:
db.collection('tableName').find({ col: 'value' }, (err, data) => {
if (err) {
// handle error
} else {
// you have data here
}
});
See: http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#find
Update
After you changed your question and posted some comments it is more clear what you want to do.
To achieve your goal of emulating the Mongo shell in Node you would need to parse the command typed by the user and execute the appropriate command while keeping in mind:
the difference between SpiderMonkey used by the Mongo shell and Node with V8 and libuv
the difference between BSON and JSON
the fact that Mongo shell works synchronously and the Node driver works asynchronously
The last part will probably be the hardest part for you. Remember that in the Mongo shell this is perfectly legal:
db.test.find()[0].x;
In Node the .find() method doesn't return the value but it either takes a callback or returns a promise. It will be tricky. The db.test.find()[0].x; case may be relatively easy to handle with promises (if you understand the promises well) but this will be harder:
db.test.find({x: db.test.find()[0].x});
and remember that you need to handle arbitrarily nested levels.
The Mongo protocol
After reading some of the comments I think it's worth noting that what you actually send to the Mongo server has nothing to do with the JavaScript that you write in the Mongo shell. The Mongo shell uses SpiderMonkey with a number of predefined functions and objects.
But you don't actually send JavaScript to the Mongo server so you can't send things like db.collection.find(). Rather you send a binary OP_QUERY struct with a collection name encoded as a cstring and a query encoded as BSON plus a bunch of binary flags. See:
https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-query
The BSON is itself a binary format with a number of low level values defined as bytes:
http://bsonspec.org/spec.html
The bottom line is that you don't send to the Mongo server anything resembling what you enter in the Mongo shell. The Mongo shell parses the things that you type using the SpiderMonkey parser and sends binary requests to the actual Mongo server. The Mongo shell uses JavaScript but you don't communicate with the Mongo server in JavaScript.
Example
Even the JSON query object is not sent to Mongo as JSON. For example, when you are searching for a document with a hello property equal to "world" you would use {hello: 'world'} in JavaScript or {"hello": "world"} in JSON but this is what gets send to the Mongo server - by the Mongo shell or by any other Mongo client:
\x16\x00\x00\x00\x02hello\x00\x06\x00\x00\x00world\x00\x00
Why it's so different
To understand why the syntax used in Node is so different from the Mongo shell, see this answer:
Why nodejs-mongodb middleware has different syntax than mongo shell?

how to use marklogic query results in node.js

I have looked around quite extensivly and could not find any example on how to use query results from the marklogic module inside node.js...
Most examples do a console.log() of results and thats it, but what if I need the query results (say in a JSON array and use these results later on?
Seems I am missing some node.js ascynch stuff here...
Example :
var marklogic = require('marklogic');
var my = require('./my-connection.js');
var db = marklogic.createDatabaseClient(my.connInfo);
var qb = marklogic.queryBuilder;
db.documents.query(
qb.where(qb.parsedFrom('oslo'))
).result( function(results) {
console.log(JSON.stringify(results, null, 2));
});
// I would like to use the results here
// console.log(JSON.stringify(results, null, 2))
Now question is I would like to use the results object later on in this script. I have tried using .then(), or passing it to a variable and returning that variable but no luck.
Regards,
hugo
Simple answer: you need to continue your business logic from the result() callback.
In more detail, your goal is to do something with the result of an asynchronous computation or request. Since JS has no native async capabilities (such as threads), callbacks are typically used to resume an operation asynchronously. The most important thing to realize is that you cannot return the result of an async computation or request, but must resume control flow after it completes. Defining lots of functions can help make this kind of code easier to read and understand.
This example illustrates what's happening:
process.nextTick(function() {
console.log('second')
})
console.log('first')
That program will log first, then second, because process.nextTick() asynchronously invokes the callback function provided to it (on the next turn of the event loop).
The answers at How do I get started with Node.js offer lots of resources to better understand async programming with node.js.

Function with mongodb find does not return result

I am trying to return a Mongo result when I call a function in Swig template. It does not wait for the mongo result and continues rendering the template.
Example code:
function swigfunction(){
db.collection('contentitems').find({}).toArray(function(err, docs) {
//generated my output
return myoutput;
});
}
Then I try to call the function, but "undefined" gets returned.
{{ swigfunction() }}
Please help
The MongoDB API uses an asynchronous callback mechanism. That means instead of just idling and wasting resources, the program will continue while the database processes your request. When the response from the database finally arrives, the callback function return myoutput; is executed.
The usual pattern in node.js is to nest all your asynchronous function calls and write the output in the innermost callback function.
You can use mongo-sync sync mongo-db client library.

Resources