In the terminal of my IntelliJ, I am able to call "node mongoDB.js" and retrieve the sample data in my database. However, when I go to launch the index.html page, I am given an error at the console screen of: "Uncaught ReferenceError: require is not defined mongoDB.js:1 at mongoDB.js:1" I tried to see if the button wasn't working to javascript error but was able to get a hard-coded word to appear. Any help would be appreciated. Code below:
async function main() {
const uri = "mongodb+srv://<usr>:<pass>@cluster0.dfgj3.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
const client = new MongoClient(uri);
try {
await client.connect();
await listDatabases(client);
} catch (e){
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
async function listDatabases(client) {
const databasesList = await client.db().admin().listDatabases();
console.log("Databases:");
databasesList.databases.forEach(db => console.log(` - ${db.name}`));
};
function displayQuery() {
let text1 = "Hello";
document.getElementById("query").innerHTML = text1;
}
displayQuery();
<html>
<head>
<meta charset="UTF-8">
<title>TITLE</title>
<script src="fetchAPI.js" type="text/javascript"></script>
<script src="mongoDB.js" type="text/javascript"></script>
<link href="styles.css" rel="stylesheet">
</head>
<body>
<div class="my-grid">
<p class="span-three">
NOTE: ticker AAPL is just arbitrary
Stock: <input id = "ticker" value = "AAPL"></input>
<br/>
<button onclick="displayQuery()" id= "submit" >Submit</button>
<p id="query"></p>
</p>
</div>
</body>
</html>
MongoDB is server side only. You are trying it to call it in a front page. These are different things.
In order for your webpage to load data from your db you should create an API . The api would retrieve the data and send it back to you
Here is a link from an official forum https://www.mongodb.com/community/forums/t/why-doesnt-mongodb-work-with-client-side-js/9062