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

Stitch service EJSON

Hello friends!

I am working with an Incoming Webhook. When i do this:

exports = function(payload, response) {

var collection = context.services.get("mongodb-atlas").db("FEDEX").collection("empleado");
var retorno = collection.findOne();
return retorno;

};

Returns well but in EJSON format:

{
horaMarcaje: { ‘$date’: { ‘$numberLong’: ‘1576802718000’ } },
tipoMarcaje: { ‘$numberInt’: ‘0’ },
SN: ‘BWXT191960344’,
tipoLector: ‘huella’
}

I try to solve it this way:

exports = function(payload, response) {

var collection = context.services.get("mongodb-atlas").db("FEDEX").collection("empleado");
var retorno = collection.findOne();

response.setHeader("Content-Type", "application/json");
response.setBody(JSON.stringify(retorno));
response.setStatusCode(200);

};

But I get this: {}

How do I get the function to return a JSON instead of an EJSON?

Thanks!

I would use https://docs.mongodb.com/stitch/functions/utilities/ to convert the answer.

1 Like

I could fix it!
Problem with promises. I was missing the await in:

var data = await collection.findOne();

This works perfect:

exports = async function(payload, response) {

try {
var collection = context.services.get(“mongodb-atlas”).db(“FEDEX”).collection(“empleado”);
var data = await collection.findOne();

    var dataJson = JSON.stringify(data);
           
    response.setHeader("Content-Type", "application/json");
    response.setBody(dataJson);
    response.setStatusCode(200);
  }

catch(error) {
console.error(error);
}
};

I don’t think you need to await the JSON.stringify function. Its sync.

1 Like

What do you mean? Do you mean you want the date in some other format? Can you show what format you need back?

1 Like

Thanks Asya!

The issue was that I didn’t know how to respond with JSON instead of EJSON.

But I could fix it

Thank you!

1 Like

Thanks Ihsan!

I could solve it, the problem was that I was missing the “await” in the query:

var data = await collection.findOne ();

Thank you!

1 Like