0

Consider:

const { MongoClient } = require('mongodb');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'aaaaa';

// Create a new MongoClient
const client = new MongoClient(url);

// Sample fruits to insert
const fruits = [
  { name: 'Apple', color: 'Red' },
  { name: 'Banana', color: 'Yellow' },
  { name: 'Orange', color: 'Orange' },
  // Add more fruits here
];

async function insertFruits() {
  try {
    // Connect to the MongoDB server
    await client.connect();

    // Select the database
    const db = client.db(dbName);

    // Get the "fruits" collection
    const collection = db.collection('fruits');

    // Insert the fruits into the collection
    const result = await collection.insertMany(fruits);

    console.log(`${result.insertedCount} fruits inserted.`);
  } catch (error) {
    console.error('Error:', error);
  } finally {
    // Close the connection to the MongoDB server
    client.close();
  }
}

// Call the function to insert fruits
insertFruits();

It is not connecting to the server. How do I connect to my MongoDB server? The problem is not with the server. It is working while using Python, but it’s not working with JavaScript. How do I make it work and remove the error which I am getting in my terminal?

Error: MongoServerSelectionError: connect ECONNREFUSED ::1:27017
    at Timeout._onTimeout (D:\Programming\webDEv UDemy\MongoDb\node_modules\mongodb\lib\sdam\topology.js:278:38)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined,
  [Symbol(errorLabels)]: Set(0) {}
}

This is what I am getting.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • The text was completely out of whack with the code. Was the code generated by some tool? Or was it from some standard example (`const collection = db.collection('fruits');` is found in [this question](https://stackoverflow.com/questions/69525092/mongoclient-not-connected-error-while-trying-to-use-mongoose))? – Peter Mortensen Aug 17 '23 at 19:23

0 Answers0