DEV Community

Discussion on: A crash course on Serverless APIs with Express and MongoDB

Collapse
 
adnanrahic profile image
Adnan Rahić

It's already cached. Check this comment. 😄
I'm glad you found this article helpful!

Collapse
 
srujanjawaji profile image
srujanjawaji

I saw the comment, but was a bit confused when I saw your other post on scaling issues with Serverless & mongoDB, where you had taken care of re-using the connection in the code & in this article there is no caching related code. So how is it cached without any explicit code? does the mongoose.connect take care of not creating a new connection when there is an open connection?

Collapse
 
srujanjawaji profile image
srujanjawaji

What I mean is, in your other couple of courses you have used the below code in db.js to re-use existing connection, but not in this course, so I am wondering how is it cached & re-used for subsequent requests.

Code I am referring to, from other courses:
const mongoose = require('mongoose');
let isConnected;

module.exports = connectToDatabase = () => {
if (isConnected) {
console.log('=> using existing database connection');
return Promise.resolve();
}

console.log('=> using new database connection');
return mongoose.connect(process.env.DB) // keep the connection string in an env var
.then(db => {
isConnected = db.connections[0].readyState;
});
};

Thread Thread
 
adnanrahic profile image
Adnan Rahić

You see the isConnected variable?
That's what's checking if the mongoose connection is established. If it's true then mongoose won't connect again. 😄

Thread Thread
 
srujanjawaji profile image
srujanjawaji

The logic with isConnected variable, that I mentioned in my previous reply is from your other posts, but in this post you seem to have no used this logic with isConnected variable in the db.js, so that's why I was confused.
So are you saying this isConnected logic is needed so that every request doesn't create a new connection?

I understand that this is a 2 years old post & you may not remember what is in the code of this post versus the other posts of your.
So, request you to please check & confirm if the db.js code mentioned in this post also uses cached connection & if yes how?

For your quick reference below is the db.js code in this post:

// ./lib/db.js
const mongoose = require('mongoose')
mongoose.connect(process.env.DB)