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.

Dear @jhona_kkk, I am starting to follow you because your are a SPAMMER. This way I will catch your SPAM faster.

I flagged your previous post as SPAM.

In Mongoose, a popular Node.js library for MongoDB, you can define a schema for your data and then create a model based on that schema. When you have relationships between different types of data, you can use Mongoose’s support for population to establish connections between documents.

Let’s consider an example where you have two models: Author and Book, and you want to establish a connection between them. Each book will have a reference to its author.

javascriptCopy code

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Define Author schema
const authorSchema = new Schema({
  name: String,
  books: [{ type: Schema.Types.ObjectId, ref: 'Book' }]
});

// Define Book schema
const bookSchema = new Schema({
  title: String,
  author: { type: Schema.Types.ObjectId, ref: 'Author' }
});

// Create models based on the schemas
const Author = mongoose.model('Author', authorSchema);
const Book = mongoose.model('Book', bookSchema);

// Example usage
const newAuthor = new Author({ name: 'John Doe' });
const newBook = new Book({ title: 'Sample Book', author: newAuthor._id });

// Save author and book
newAuthor.save()
  .then(() => newBook.save())
  .then(() => {
    // Add the book to the author's books array
    newAuthor.books.push(newBook);
    return newAuthor.save();
  })
  .then(() => {
    // Populate the author field in the book document
    return Book.findOne({ title: 'Sample Book' }).populate('author');
  })
  .then((populatedBook) => {
    console.log(populatedBook);
  })
  .catch((error) => {
    console.error(error);
  });

In this example, the Author schema has a field called books which is an array of ObjectId references to Book documents. The Book schema has an author field that is a single ObjectId reference to an Author document.

When you save an author and a book, you can establish the connection by pushing the book’s _id to the author’s books array and saving the author again. The populate method is then used to retrieve the full author details when querying a book.

Remember to establish a connection to your MongoDB database before using these models:

javascriptCopy code

mongoose.connect('mongodb://localhost:27017/your-database', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log('Connected to MongoDB');
  })
  .catch((error) => {
    console.error('Error connecting to MongoDB:', error);
  });

Replace 'mongodb://localhost:27017/your-database' with the appropriate connection string for your MongoDB server.