Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

node.js - How to use existing mongoose connection rather than creating new mongoose connection each time or on each REST API's request

My requirement is that- i want to create new mongo database connection for each subdomain as subdomain name is coming with request's header ---- i have done this as i pass that subdomain name into await mongoose.createConnection(mongodb://localhost/${subdomainName}, but with this approach if 500 request coming from a subdomain then 500 times mongoose connection is made--- i want only while first request mongoose connection should be created and while remaining 499 request that existing connection should be used -- because there is no meaning of creating new connection on each request if already have the same connection

EXAMPLE STEP1: if there is a request coming from subdomain today.mydomain.com then it creates a new mongodb connection and db name as "today" --- THAT IS OK

STEP 2: if next time any other request is coming from same domain then again connection is made but this time this time new mongoose connection should not be created ----- but existing connection of today db which was created in first request should be used

But i want if there is already mongodb connection made for a subdomain and next time when any request coming from that subdomain at that time new mongoose connection should not be created --- the existing connection which is already created WHILE FIRST REQUEST OF THAT DOMAIN should be used

IS THERE ANY WAY THAT MONGOOSE PROVIDE WHERE I CAN FIND THERE IS ALREADY CONNECTION IS MADE FOR THE DOMAIN IF IT WILL RETURN TRUE THEN I WOULD USE THAT CONNECTION WITHOUT CREATING NEW ELSE i would create a new connection

I AM USING FOLLOWING CODE--

let CURRENT_DB = await mongoose.createConnection(`mongodb://localhost/${subdomainName}`);
question from:https://stackoverflow.com/questions/65882429/how-to-use-existing-mongoose-connection-rather-than-creating-new-mongoose-connec

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...