2

I'm just learning JavaScript and Nodejs, based on some code I found online, I wrote the below application. When I try to run it I get an error on line 9, where it says "new MongoClient". The erroe says that "MongoClient is not a constructor". Could you please explain the issue and how to fix it? Thanks for your responses!

code:

const MongoClient = require('mongodb').MongoClient;
const Server = require('mongodb').Server;

async function main(){
  console.log("Starting main");
  console.error(`error in main`);
  const uri = "mongodb+srv://miniMurali:Snowyndm@cluster0-5jxw4.mongodb.net/test? 
retryWrites=true&w=majority&useUnifiedTopology=true";


  const client = new MongoClient(new Server(uri)); //***error here***
//const mongodb = context.services.get("mongodb-atlas")

//To delete later
//await client.connect();
//await listDatabases(client);

try{

    //await client.connect();
    var MongoClient
    const Booths = client.db("client").collection("booths");
    const Vendors= client.db("client").collection("vendors");
    const db = client.db("client");
    const collections = db.getCollectionNames();

    console.log("Starting DB processing");

    await listDatabases(client);
    await addSampleData(Booths, Vendors);
    await readSampleData(Booths, Vendors);
    await searchBooths(db);
    await deleteData(Booths, Vendors);
} catch (e){
    console.error(e);
}

finally {
    await client.close();
}


//main(). catch(console.error);

}
async function listDatabases(client){
    databasesList = await client.db().admin().listDatabases();
    console.log("Databases:");
    databasesList.databases.forEach(db => console.log(`-${db.name}`));
};



//to be deleted later, sample data in order to add functions that organize it later
async function addSampleData(Booths, Vendors){

    const booth1 = {'number': 1,
     location:"lowerCommons", "outlets":2, size:"10 x 10", "vendorID": "none"}
    let vendor1= {"vendorID": 1, "name": "Doggo", "business": "Puppy", "phone1":"111-111-1111", 
"email": "TennisBall@puppup.net", "phone2":"none", "tables": 3, "boothsAllocated":"yes", 
"addressLine1": "Woof woof", "city": "Slobberton", "state":"fluff"}
await Booths.insertOne(booth1)
.then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`))
.catch(err => console.error(`Failed to insert item: ${err}`));

await Vendors.insertOne(vendor1)
.then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`))
.catch(err => console.error(`Failed to insert item: ${err}`))
}


async function readSampleData(Booths, Vendors){

    var boothsA= new Array;
    boothsA.push(Booths);

    var vendorsA=new Array;
    vendorsA.push(Vendors);




        //boothsA.find(searchBooths);
}      

function searchBooths(db){

     collections = db.getCollectionNames();
    for(var i = 0; i< collections.length; i++){    
    print('Collection: ' + collections[i]); // print the name of each collection
    db.getCollection(collections[i]).find().forEach(printjson);
    } //and then print the json of each of its elements/

}

 function deleteData(Booths, Vendors){
    console.log('Booths');
}

main(). catch(console.log);

Error details:

Starting main
error in main
TypeError: MongoClient is not a constructor
  at main (C:\Users\nishu\OneDrive\Documents\GitHub\craft-fair-app\Nisha\app2.js:10:17)
  at Object.<anonymous> (C:\Users\nishu\OneDrive\Documents\GitHub\craft-fair-app\Nisha\app2.js:97:2)
  at Module._compile (internal/modules/cjs/loader.js:1157:30)
  at Object.Module._extensions..js (internal/modules/cjs/loader.js:1177:10)
  at Module.load (internal/modules/cjs/loader.js:1001:32)
  at Function.Module._load (internal/modules/cjs/loader.js:900:14)
  at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
  at internal/main/run_main_module.js:18:47
  • Look here: https://stackoverflow.com/a/40108404/2282634 – Joe Apr 05 '20 at 22:12
  • If you are learning NodeJS, JavaScript and MongoDB, I suggest you try some existing examples and understand the usage of the code and the MongoDB NodeJS APIs. Here are some examples where you can connect to the database and perform CRUD (create, read, update and delete) operations on the database data: [MongoDB NodeJS quick start](https://mongodb.github.io/node-mongodb-native/3.5/quick-start/quick-start/). In your present code you are trying to do lot of things and not clear about them. Try working with one database and one collection, to start with. – prasad_ Apr 06 '20 at 01:56
  • Hi there! As far as MongoDB connection is concerned, your code seem alright, the only thing that is fishy is the `var MongoClient` you have around line 22, becuase of Javascript variable hoisting, this MongoClient variable declaration which has a value of undefined might override what you imported from the `mongodb` library. Can you try removing that variable declaration and see if it fixes the error? – Tunmee Apr 06 '20 at 10:29

0 Answers0