MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

Stitch parse EJSON result from find()

In my function below I am trying to get all the ObjectIDs in ‘mycollection’. Since the find function returns an EJSON object when I log the output I just see ‘{ }’. I cannot manage to output the ObjectIDs, can anyone point me in the right direction please?
(I know the result is not empty by the way, as it outputs the correct JSON-looking object in the console)

exports = async function(){

      const mongodb = context.services.get("mongodb-atlas");
      const collection = mongodb.db("mydatabase").collection("mycollection");
      
      var result = {};
      var resultJson = {};
      
      try { result = await collection.find({}, {_id:1})
      
        resultJson = JSON.stringify(result);

      }
      catch (e){
         console.log(e);
      }

    console.log('res', resultJson)

    return result;
};

Hi @Daniel_Gold,

The collection.find() returns RemoteMongoReadOperation. You need to call its methods to return Promise object. For example toArray():

result = await collection.find({}, {_id:1}).toArray();

This is slightly different than collection.findOne(), which returns Promise for the resulting document. i.e.

result = await collection.findOne({}, {_id:1});

Regards,
Wan.

1 Like

Thanks very much that’s really helpful - saved me a lot of time!