Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Mongoose connections in Azure Function

Can you create one Mongoose connection and use it with all of your functions?

I am creating a serverless API using Azure Functions which connects to a database using Mongoose. I'm trying to understand the relationship between my API and the Mongoose connection.

My previous understanding was that each function must establish its own connection with the database. However I am noticing some odd behavior in my code. When I open a connection in one function, I can access that connection in any other function. Is this expected behavior? Example:

Function A

...
const mongoose = require('mongoose');
const User = require('../models/UserModel');
...

// Connect to database
mongoose.connect(process.env.CosmosDBConnectionString, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});
mongoose.connection.on('connected', () => {
  console.log('Mongoose has connected.');
});

module.exports = async function (context, req) {
...
}

Function B

const mongoose = require('mongoose');
const User = require('../models/UserModel');

module.exports = async function (context, req) {
  if (mongoose.connection.readyState == 1) {
    context.log("Mongoose is connected.");
    // readyState == 1 indicates connection is open. This code runs.
  }
  
  await User.findOne({ email: req.query.email }).then(user => {
      // I successfully retrieve user from the database    
  })
...  
}


Notice that connection is established in Function A but is used in Function B. If this is expected, would it be good or bad practice to establish a connection in one function and use it across all of my API?

like image 771
L. O'Shea Avatar asked Dec 11 '25 23:12

L. O'Shea


1 Answers

This is the default behavior: Functions in a function app share resources. Among those shared resources are connections: HTTP connections, database connections, xxxx. You can refer to this doc for more details.

And for a good practice(For your current solution, it's not good that the Function B depends on Function A), you'd better create a separate .js file which is used to connected the db, then call it in each function, just like in this article.

like image 87
Ivan Yang Avatar answered Dec 13 '25 11:12

Ivan Yang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!