I have a single Document in my mongoDb collection:
{
"_id": {
"$oid": "f8cc66adc6b5ce1fc99a2f59"
},
"isFlat": true,
"schema": {
"type": "record",
"name": "topLevelRecord",
"fields": Array[]
},
"userId": "4d18fa67-c4ca-4d89-8e52-506774a8b12c",
"filenames": [],
"createdAt": {
"$date": "2024-08-02T12:04:40.551Z"
}
}
Now, I’d like to retrieve the field “schema”.
Up till now I have done it with the toArray() function of the cursor like this:
await collection
.aggregate([
{ $match: { _id: new ObjectId(`${fileId}`) }},
{ $project: { _id: 0, schema: 1}}
])
.toArray()
This approach appears to be very time consuming. I some because the Array in the schema field can be very nested.
In the official documentation (https://www.mongodb.com/docs/drivers/node/current/fundamentals/crud/read-operations/cursor/) I learned about the other functions of the Cursor Object.
I tried the following:
cursor.stream().on("data", doc => console.log(doc));
which perfectly prints me the result I want in a very time-efficient manner but when I try to change it so that the result will be returned and attached to result, like so:
let schema = cursor.stream().on("data", doc => doc);
I get the whole Cursor Object attached to the schema variable.
Why is this the case? How to achieve the same result to be bounded to a variable then what is printed out on the console?