Question

Problems connecting my function to mongoDB

Hello, I’m trying to connect my function with my database (also on digital ocean). I tried it with mongoose and mongodb, here are the codes:

mongoose

  try {
    // await mongoose.connect('mongodb+srv://my-digitalocean-url');

    mongoose.connect('mongodb+srv://my-digitalocean-url', (err) => {
      if (err) throw new Error(err);
      console.log(`MongoDB Connection: ${mongoose.connection.readyState}`);
    });

    // console.log(`MongoDB Connection: ${mongoose.connection.readyState}`);

    return {
      body: { 'MongoDB Connection': mongoose.connection.readyState },
    };
  } catch (error) {
    return {
      body: { Connected: false },
    };
  }

I tried both methods: using await, my function returns a timeout error, even though I set it to wait for 30 seconds in project.yml; using .then in the parameters, after 30 seconds it returns a status “connecting”.

mongodb

  const client = new MongoClient('mongodb+srv://my-digitalocean-url');

  try {
    await client.connect();

    // console.log(`Connected`);

    return { connected: true };
  } catch (e) {
    console.error(e);
    return {
      body: { error: 'There was a problem adding the data to the database.' },
      statusCode: 400,
    };
  } finally {
    await client.close();
  }

MongoDB always returns a timeout error.

But the strange thing is: exactly the same code works on my local machine using node (that’s what console.logs exist for). I literally used ctrl+c ctrl+v on this, what did I do wrong?


Submit an answer
Answer a question...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Matt Welke
DigitalOcean Employee
DigitalOcean Employee badge
February 2, 2023

The code you posted doesn’t put the business logic into a function body. A deployed function must consist of a function defined at the top level of the file, called main. Example:

function main(event) {
  // business logic
}

Or, if package.json is used (because you want to use 3rd party libraries from NPM), it must be exported and called main. Example:

exports.main = function (event) {
  // business logic
}

In your case, you need to put the code that interacts with MongoDB, that starts with try {, inside the function body. And, you should put the code that requires the MongoDB library and the code that creates the MongoDB client (const client = new MongoClient('mongodb+srv://my-digitalocean-url');), outside of the function body, so that it only has to run during cold starts. That will make function execution as fast as possible once it’s warm.

Have a look at the sample functions for Node.js in our docs (https://docs.digitalocean.com/products/functions/quickstart/sample-functions/) to help you with this. And, be sure to let us know if you run into any other issues.