"Response" Object Undefined Error in App services HTTPS Endpoints

i’m trying to add a response status code in the response object instead of defining in the response body as
{
statusCode : 404 ,
data: { }
}

exports = function({ query, headers, body} , response) {
try{
console.log(“response -->” ,response);
response.setStatusCode(404);
response.setHeader(‘Content-Type’, ‘application/json’);
return response;
}
catch(e){
return e;
}
};

corresponding response :

ran at 1718340940221
took 160.456402ms
logs:
response → undefined
result:
{
“message”: “Cannot access member ‘setStatusCode’ of undefined”,
“name”: “TypeError”
}
result (JavaScript):
EJSON.parse(‘{“message”:"Cannot access member 'setStatusCode’ of undefined",“name”:“TypeError”}')

Hello Community,

i have exactly the same issue.
I have written a function, in which I use the query parameters and the response as described in: Custom Endpoint Documentation and shown in the Example

Endpoint-Function:

exports = async function(request, response){
  
  // -------------------------------------- GENERATE COLLECTION --------------------------------------
  const SERVICE_NAME = "EXAMPLE";
  const DATABASE_NAME = "EXAMPLE";
  const COLLECTION_NAME = "EXAMPLE";

  collection = context.services.get(SERVICE_NAME).db(DATABASE_NAME).collection(COLLECTION_NAME);


  // -------------------------------------- EXTRACT REQUEST PARAMETERS ------------------------------------
  const queryParams = request.query;

  var brand;
  var paramName = "Brand"
  if (queryParams && queryParams.hasOwnProperty(paramName)) {
    brand = queryParams[paramName];
    console.log(`Parameter "${paramName}" found: ${brand}`);
  } else {
    console.log(`Parameter "${paramName}" is missing in query`);
    response.setStatusCode(400);
  }

  var models;
  try {
    models = await collection.distinct("vehicle_model.model",{'vehicle_model.make': brand});
  } catch(err) {
    console.log("Error occurred while executing:", err.message);
    response.setStatusCode(500);
    return { error: err.message };
  }

  return { models: models };
};

I get the same error as @Sai_kiran2 :

{"message":"Cannot access member 'setStatusCode' of undefined","name":"TypeError"}

I faced the same issue where response object is undefined, it seems due to the specific way the response is set in MongoDB Atlas Functions.

It looks like MongoDB Atlas Functions use return for setting the response.

Here’s how you can rewrite your code:

    return {
      status: 400,
      body: { error: "Error" }
    };

The documentation should be updated accordingly :slight_smile: