Create names connection in mongoose

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

What tool did you use to help validate that? :flushed:

That should not have validated at all…

I want you to look at this script, and change yours around accordingly. Whatever plugin you used to help generate that, I highly encourage you stop using it.

const mongoose = require('Mongoose');
mongoose.connect("MongoDB://localhost:<PortNumberHereDoubleCheckPort>/<DatabaseName>", {useNewUrlParser: true});
const <nameOfDbschemahere> = new mongoose.schema({
  name: String,
  rating: String,
  quantity: Number,
  someothervalue: String,
  somevalue2: String,
});

const Fruit<Assuming as you call it FruitsDB> = mongoose.model("nameOfCollection" , <nameOfSchemeHere>);

const fruit = new Fruit<Because FruitsDB calling documents Fruit for this>({
  name: "Watermelon",
  rating: 10,
  quantity: 50,
  someothervalue: "Pirates love them",
  somevalue2: "They are big",
});
fruit.save();

@Prasanna_Sasne

If you need the catch block, etc.

const mongoose = require('mongoose');

// Connect to database
const connection = mongoose.createConnection("mongodb://localhost:<PortNumberHereDoubleCheckPort>/<DatabaseName>", {useNewUrlParser: true});

// Connections
connection.on('connecting', function() {
  console.log('Connecting to database...');
});

connection.on('connected', function() {
  console.log('Connected to database');
});

connection.on('error', function(err) {
  console.error('Error in database connection: ' + err);
});

connection.on('disconnected', function() {
  console.log('Disconnected from database');
});

// Schema generation
const FruitSchema = new mongoose.Schema({
  name: String,
  rating: Number,
  quantity: Number,
  someothervalue: String,
  somevalue2: String,
});

const Fruit = connection.model("nameOfCollection" , FruitSchema);

// Document to save.
const fruit = new Fruit({
  name: "Watermelon",
  rating: 10,
  quantity: 50,
  someothervalue: "Pirates love them",
  somevalue2: "They are big",
});

fruit.save(function(err, doc) {
  if (err) {
    console.error('Error saving fruit: ' + err);
  } else {
    console.log('Fruit saved successfully: ' + doc);
  }
});

This validates, and you’re welcome to use it however you want and modify.

This is another script example I posted a while back.

#!/usr/bin/env node
import { MongoClient } from 'mongodb';
import { spawn } from 'child_process';
import fs from 'fs';

const DB_URI = 'mongodb://0.0.0.0:27017';
const DB_NAME = 'DB name goes here';
const OUTPUT_DIR = 'directory output goes here';
const client = new MongoClient(DB_URI);

async function run() {
  try {
    await client.connect();
    const db = client.db(DB_NAME);
    const collections = await db.collections();

    if (!fs.existsSync(OUTPUT_DIR)) {
      fs.mkdirSync(OUTPUT_DIR);
    }

    collections.forEach(async (c) => {
      const name = c.collectionName;
      await spawn('mongoexport', [
        '--db',
          DB_NAME,
        '--collection',
          name,
        '--jsonArray',
        '--pretty',
        `--out=./${OUTPUT_DIR}/${name}.json`,
      ]);
    });
  } finally {
    await client.close();
    console.log(`DB Data for ${DB_NAME} has been written to ./${OUTPUT_DIR}/`);
  }
}
run().catch(console.dir);

Thank you for your reply,
but I am not using any tool.
Inside connection.on(‘error’) I am rejecting the promise. Ignore the Try/catch block from my code. but still, a server is crashing. I am getting exact same error for an invalid connection string. Using an IP address is not the solution. I want to handle errors properly.