Return JSON from function instead of EJSON - cant get JSON.stringify to work?fun

Sorry, complete new person, apologies for errors in posting. I’ve read the support documentation re EJSON, but can’t make it work. This is a simple function, accesses a collect and returns JSON. I was trying to make it regular JSON , but it’s only working for me with extended JSON.

// This function is the endpoint's request handler.
exports = function({ query, headers, body}, response) {
    const {email, password} = query;
    const doc = context.services.get("mongodb-atlas").db("xxxx").collection("xxxxxxxx");
    bobQ = {"email": {$eq: email}, "password": {$eq: password}}
    const responseCall = doc.findOne(bobQ);
    return JSON.stringify(responseCall);
    // return responseCall;
};

This is returned without stringify, with stringify, “{}” is returned:

{
    "_id": {
        "$oid": "6215f8344fbd568f13ba6bbb"
    },
    "userId": {
        "$numberInt": "18"
    },
    "email": "xxxxx@outlook.com",
    "subscription": {
        "type": {
            "$numberInt": "0"
        }
    },
    "password": "awe43es"
}

Hi @Robert_Benson and welcome in the MongoDB Community :muscle: !

I think it’s because findOne() returns a promise and you are returning a promise instead of the actual response you are expecting.

exports = function({ query, headers, body}, response) {
    const coll = context.services.get("mongodb-atlas").db("covid19").collection("global");
    coll.findOne().then(res => {
      response.setBody(JSON.stringify(res));
    });
};

This should work!

Cheers,
Maxime.

2 Likes

It does work, thank you so much. I’ve modified my function as below :

exports = function({ query, headers, body}, response) {
  const {email, password} = query;
  bobQ = {"email": {$eq: email}, "password": {$eq: password}};
  const coll = context.services.get("mongodb-atlas").db("have-a-nice-day").collection("thanks");
  coll.findOne(bobQ).then(res => {
    response.setBody(JSON.stringify(res));
  });
}
1 Like

Check out this blog post if you want to see a REST API with a bit more “options”.

Cheers,
Maxime.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.