Publishing to Google PubSub

I’ve been trying to set up a publishing function in MongoDB functions that’s called when a change in a collection activates a trigger. Problem is whenever I test it by updated a document, the trigger logs show the same error: ‘Received error while publishing: Data must be in the form of a Buffer.’

I’m pretty sure the publishMessage call is triggering it, but I don’t know why.

Has anyone successfully set up a MongoDB function to communicate with a Google pub sub?

Did you go about it this way or find an alternative?

Any advice would be greatly appreciated.

exports = async function(document, topicName){
  
  const {PubSub} = require("@google-cloud/pubsub");
  const avro = require("avro-js");
  
   const pubSubClient = new PubSub();
   const topic = pubSubClient.topic(topicName);
   
   const data = JSON.stringify(document);
   const dataBuffer = Buffer.from(data);

  try {
    const response = await topic.publishMessage({ data: dataBuffer });
  } catch (error) {
    console.error(`Received error while publishing: ${error.message}`);
    process.exitCode = 1;
  }

};
1 Like