What is driver command for displaying query results?

My last question for this course is pertaining to how we can log i.e. console.log the results of a find query?

I realize pretty() isn’t possible with this driver. Is there a way?

thanks

You can use the following function for JSON

console.log(JSON.stringify({ a:11, b:22, aa:{ aa1 : 3} , c:33 }, null, 4));

below is the link to JSON.stringify on MDN.

1 Like

I’m so confused about what you’re talking about. Did you read my question at all?

Consider that you have the following collection :

Screenshot%20from%202019-03-08%2023-16-18

if you are using the find command and trying to log the result using console.log
const res = await db.collection(“collection”).findOne({});
console.log(res);

the log result will look like
Screenshot%20from%202019-03-08%2023-51-45

if you change the console.log to:
Screenshot%20from%202019-03-08%2023-59-07

then the output will look like:
Screenshot%20from%202019-03-08%2023-58-37

this will look like the pretty function, but using the NodeJS driver.

Hope that answer the question.

Ok it needs to be in promise form. Let me try that.

thanks for the reply. the findOne works but whey not the find({}) ? this doesnt’ work and just spills out it’s guts of paremeters not the query.

The difference between find (return a Cursor) and findOne (return a document) affect the output you are getting.

You have to iterate each document that is returned in the cursor using the “find” function.

try using forEach function to iterate each document:

1 Like

ding ding ding… lol i am little confused as to am I supposed to know that? um I don’t know. This is kind of what I mean that a lesson with the driver would be supper supper helpful. thanks for your replies.

just to ask… Is the find output an array of some sort? I am not seeing this in the output of the object.

you can use the function toArray() appended to the find(), this will transform the result from the find() to an array (instead of a cursor you will fill the result in an array)

const res = await db.collection(“sun”).find().toArray(function(item) {
console.log(JSON.stringify(item,null,4));
});

Note: dumping the find() result to an array will use memory and not recommended for large result.

Not sure this is answer your question, but the find() result cursor is not an array but if you think of it logically, the cursor is an index to the current list of document and you iterate to the next document in that list using different functions: forEach() or next().