1

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?

It'sNotMe
  • 1,184
  • 1
  • 9
  • 29
  • 1
    Have you tried `return requestLogs.insertOne(...)`? – Chris Bush Jun 11 '19 at 14:36
  • Thank you for the suggestion. I just tried that and the same TypeError was returned. – It'sNotMe Jun 12 '19 at 00:22
  • 1
    I'm sorry, I copied your steps but was not able to reproduce the issue. When I use your exports in the Function Editor console, I do get an error with the fact that `response` is undefined, but I can work around this by mocking out the second parameter: `exports({query: {arg1: 'hello', arg2: "world!"}, body:BSON.Binary.fromText('{"msg": "world"}')}, {setStatusCode: () => {}, setBody: () => {}})`. If you are still having issues, you might also get answers on the [MongoDB community slack](https://launchpass.com/mongo-db) #stitch channel. – Chris Bush Jun 12 '19 at 20:01

1 Answers1

0

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.

It'sNotMe
  • 1,184
  • 1
  • 9
  • 29