Webhook iteration issue

I am facing an issue while iterating the cursor inside a webhook. The highlighted section does not work inside webhook , but works inside a standalone Nodejs program.

https://docs.mongodb.com/manual/reference/method/db.collection.find/#crud-read-cursor

Also, tried cusrsor.hasNext() , not working inside webhook.

Seems that I am missing some small piece. Please let me know the possible issue/resolution.

Webhook code :

let posData = context.services.get("mongodb-atlas").db("MyDB").collection("MyCollection");

result = posData.find(body);

console.log("return document length" ,result.length);

await result.forEach(obj=>{

console.log(ojb);

});

Error:

{“message”:"‘forEach’ is not a function"}

Can you please suggest what am I missing ?

I believe you need to use toArray before applying the forEach - here is an example: https://docs.mongodb.com/realm/mongodb/find-documents/

toArray does not work as well.

Can you try the following snippet, I believe this should work:

  const collection = context.services.get('mongodb-atlas').db('grocery').collection('items');
  const query = {};

result = collection.find(query);


await collection.find(query)
  .toArray()
  .then(items => {
    items.forEach(console.log)
    return items
  })
  .catch(err => console.error(`Failed to find documents: ${err}`))

return "hello"
};