I am trying to create a new instance of the Mongoose on demand. In my application, one Mongoose instance is already active and i wanted to create another Mongoose instance that would be limited to a particular scope. I am accessing another collection through this instance. So i want a way to create an instance and close that instance once CRUD operations are done. But Keep open global instance. I am not able to achieve this condition. Can someone please suggest to me the way out?
I tried the below code, but even with a try-catch block, my server is crashing when invalid connection string is provided.
return new Promise((resolve, reject) => {
try {
const conn = mongoose.createConnection(`${url}/MyProjectDB`, {
serverSelectionTimeoutMS: 2000
});
// Listen for the error event on the named connection
conn.on('error', () => {
console.log('Mongoose default connection error');
reject(`Unable to connect ${url}.`);
// conn.close();
//throw new Error('Something went wrong');
});
conn.on('connected', () => {
const myCollectionDoc = conn.model('myCollection', myCollectionSchema);
myCollectionDoc.find({})
.then((documents: Array<documentType>) => {
resolve({ ConnectionString: url, Data: documents });
})
.catch(() => {
reject('Unable to fetch documents.');
})
.finally(() => conn.close());
});
} catch (err) {
reject(`Unable to connect ${url}.`);
}
})
Error -
const timeoutError = new MongoServerSelectionError(MongoServerSelectionError: Server selection timed out after 2000 ms