Question

Problems with connecting my function to mongoDB

I’m trying to connect my function with my mongodb database (also on digitalocean) but I can’t. I already tried it with Mongoose and MongoDB, here are the codes:

Mongoose:

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

    mongoose.connect('mongodb+srv://my-digital-ocean-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’ve tried both methods: using await, the function returns a timeout error, even if I set the timeout to 30 seconds in project.yml; using .then in the parameters, I always get a “connecting” status.

  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: { connected: false },
      statusCode: 400,
    };
  } finally {
    await client.close();
  }

Using mongodb, i always get a timeout error.

But the weird thing is: the exact same code works using the node command on my machine (that’s what the console.log is for). I literally used ctrl+c ctrl+v on this, what did I do wrong?


Submit an answer


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.

Bobby Iliev
Site Moderator
Site Moderator badge
December 20, 2022
Accepted Answer

Hi there,

Do you have Trusted Sources enabled for your MongoDB database cluster? If this is the case you would need to either:

Hope that this helps!

Best,

Bobby

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel