Search code examples
mongodbmongodb-atlasmongodb-stitch

'then is not a function' in MongoDB Stitch Webhook


The MongoDB Stitch Webhook docs describe my precise use case: using a POST method to call insertOne then return the inserted _id.

I pasted the example below (directly from the docs) into the Stitch Function Editor.

exports = function(payload, response) {
  const mongodb = context.services.get("mongodb-atlas");
  const requestLogs = mongodb.db("test").collection("requestlogs");
  requestLogs.insertOne({
    body: EJSON.parse(payload.body.text()),
    query: payload.query
  }).then(result => {
    response.setStatusCode(201);
    response.setBody(result.insertedId);
  })
};

I executed the function in the Function Editor console by calling:

exports({query: {arg1: 'hello', arg2: "world!"}, body:BSON.Binary.fromText('{"msg": "world"}')})

An error is returned indicating that .then is not a function.

error: TypeError: 'then' is not a function

Are the docs wrong, or I have I gone astray?


Solution

  • Certain methods, like .then, throw errors in the function editor. In my case, this was a shortcoming of the function editor, rather than an error in my code. Calling the webhook with fetch or Postman, the function executed as expected.

    The Incoming Webhook docs contain a special note:

    If you want to debug a webhook function response from the function editor, you must manually provide the HTTP response object when you run the function.

    exports( { body: "This document is the webhook payload" }, new HTTPResponse() )

    That alerted me to the idiosyncratic nature of the function editor as a JS handler. Using Postman I confirmed the function ran without errors when called. The error generated by the function editor was a red herring.