Best practice for connecting MongoDB with Node using Mongoose.
MongoDB

Best practice for connecting MongoDB with Node using Mongoose.

MongoDB TypeScript

Connect your Node.js server to MongoDB through Mongoose with optimizing performance, ensuring stability, and handling errors gracefully. Let’s explore Mongoose’s advanced configuration options for managing database connections like a pro! ?



1?? Connection Timeout (serverSelectionTimeoutMS):

serverSelectionTimeoutMS config ensures that if your MongoDB server takes too long to respond, the connection attempt fails instead of hanging forever.
mongoose.connect(DB_URL, {
  serverSelectionTimeoutMS: 5000,
});        


2?? Automatic Reconnection (autoReconnect)

This option ensures that Mongoose will automatically reconnect if it loses the connection to the MongoDB server
mongoose.connect(DB_URL, {
  autoReconnect: true,
});        


3?? Keep Alive (keepAlive)

keepAlive option ensures the connection remains open by periodically sending an empty package to MongoDB. It prevents the connection from dropping due to network inactivity.
mongoose.connect(DB_URL, {
  keepAlive: true,
  keepAliveInitialDelay: 300000, // 5 minutes
});        


4?? Use New URL Parser (useNewUrlParser)

useNewUrlParser option addresses a bug in the original MongoDB connection string parser.
mongoose.connect(DB_URL, {
  useNewUrlParser: true,
});        

5?? Unified Topology (useUnifiedTopology)

useUnifiedTopology option is newer versions of Mongoose to maintain compatibility and reduce bugs with connections.

mongoose.connect(DB_URL, {
  useUnifiedTopology: true,
});        



Finally, the image below includes all popular configurations with Mongoose and Typescript.

all config


要查看或添加评论,请登录

Sarwar Hossain的更多文章

社区洞察

其他会员也浏览了