mongodbexpresscollectionsatlas

Why Mongodb collection is not connecting via connect your application?


When i try with mongoose ,it connects. But whrn i am tring with connect with your application and mongoclient this code does not work. But this code is in their documnetation. Why Mongodb collection is not connecting via connect your application?

const express = require('express');

const app = express();
const password = "Kr6bdMTskY3rYwF4";

app.get('/', (req, res) => {
    res.send('hello i am working')
})

const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://organicUser:Kr6bdMTskY3rYwF4@cluster0.iz1nfji.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
client.connect(err => {
    const collection = client.db("organicdb").collection("products");
    // perform actions on the collection object
    console.log("Database connected");
    client.close();
});

app.listen(3000);

Why Mongodb collection is not connecting via connect your application?


Solution

  • Your Express application is working but you forgot the app.listen function. You need to assign a port to your app and make it listen to that port. Also your Mongodb error is solved.

    const express = require('express');
    
    const PORT = 3000;
    const app = express();
    const password = "Kr6bdMTskY3rYwF4";
    
    app.get('/', (req, res) => {
        res.send('hello i am working')
    })
    
    const { MongoClient, ServerApiVersion } = require('mongodb');
    const uri = "mongodb+srv://organicUser:Kr6bdMTskY3rYwF4@cluster0.iz1nfji.mongodb.net/?retryWrites=true&w=majority";
    const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
    
    async function run() {
      try {
        const database = client.db("organicdb");
        const collection = database.collection("products");
        // perform actions on the collection object
        console.log(collection);
      } finally {
        await client.close();
      }
    }
    run().catch(console.dir);
    
    app.listen(PORT, () => {
      console.log(`App listening on port ${PORT}`)
    })