I am trying to connect to a MongoDB cluster that I have using a react app created in Ionic. I created a javascript file called testMongoConnection.js that I am using to execute the connection using this tutorial from the MongoDB docs: https://docs.atlas.mongodb.com/tutorial/connect-to-your-cluster/
I can make the connection when running a node command from the cli ex: node .\testMongoConnection.js. But when I try to import my TestConnect function into a react page called homePage.tsx I am getting an error that says
"TypeError: MongoClient is not a constructor". This error is coming from line 4 of my testMongoconnection.js file which I will include below. I found this similar question here How to fix an MongoClient is not a constructor error but no one has answered it.
I know that Ionic apps cannot connect directly to MongoDB so I was planning on pushing my app to a Heroku server and running it from there which I understand to be a workaround but I am unsure about this part. My main question is why I am getting this TypeError and how do I fix it? Thanks for your responses!
Here is my homePage.tsx file
import { IonButton, IonContent, IonHeader, IonPage, IonTitle, IonToolbar } from '@ionic/react';
import ExploreContainer from '../components/ExploreContainer';
import './Tab1.css';
import { TestConnect } from './testMongoConnection.js';
const Tab1: React.FC = () => {
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>Home Page</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent fullscreen>
<IonHeader collapse="condense">
<IonToolbar>
<IonTitle size="large">Home Page</IonTitle>
</IonToolbar>
</IonHeader>
<ExploreContainer name="Home Page" />
<IonButton routerLink="/mongoConnect">mongoConnect</IonButton>
<TestConnect></TestConnect>
</IonContent>
</IonPage>
);
};
export default Tab1;
And here's my testMongoConnection.js file
export function TestConnect() {
const { MongoClient } = require("mongodb");
const url = "mongodb+srv://nojackson99:RhnnwFbgXZbhWJUE@cluster0.vs1qs.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
const client = new MongoClient(url);
// The database to use
const dbName = "Cluster0"
console.log("in function")
async function run() {
try {
await client.connect();
console.log("Connected correctly to server");
const db = client.db(dbName);
// Use the collection "people"
const col = db.collection("leaderboard");
// Construct a document
let testDocument = {
"username": "noah",
"score": 15000
}
// Insert a single document, wait for promise so we can read it back
const p = await col.insertOne(testDocument);
// Find one document
const myDoc = await col.findOne();
// Print to the console
console.log(myDoc);
} catch (err) {
console.log(err.stack);
}
finally {
await client.close();
}
}
run().catch(console.dir);
return (
<div></div>
)
};