简体   繁体   中英

MongoClient.connect doesn't work in a website's onload function

I'm still learning javascript, and I was trying to write a website that would load information from a MongoDB database into the site. These are the relevant parts of the site:

<body onload="intro()">
    <h2 id="rh1"></h2>
    <script src="bgs/roomsbg.js"></script>
</body>

Now, the roomsbg.js file looks like this:

const MongoClient = require("mongodb").MongoClient;

function intro(){
    alert("In intro");
    var roomsy;
    MongoClient.connect("<the connection string>", { useNewUrlParser: true }, function(err, db){
        if (!err){  
            var dbo = db.db("tin_project");
            dbo.collection("Pokoj").find({}).toArray(function(err, result){
                if (err) throw err;
                document.getElementById("rh1").innerHTML = result[0].nazwa_pokoju;
                db.close();
        });}});
}

I know that the script itself works, as I've tried it out on its own and it gave me the right data. I also know that the website can reach the intro() function, as it loads the alert. But it doesn't do anything beneath that. I've tried putting the require within the function, and then the alert after that, but it doesn't even load the alert then. I've tried putting an alert within the function in MongoClient.connect, but it also doesn't show up.

What am I doing wrong?

By doing a simple google search for "hello world node mongo express" or "tutorial mongo express" you will get lots of helpful articles to show you how to build a simple node application that uses express to generate HTML which pulls data from a mongo database.

This article was near the top of my search results, you could follow along with this and get a quick win. But what I would really recommend is aa course from say udemy where you can learn how to build a dynamic website using node and express. There are loads of courses and often you get what you pay for but This course is free, I've not sat it, so i cant vouch for it but you cant argue with free.

To sum up i would say given your question and your misunderstandings i would say that a course of some kind would be beneficial to you, you need to understand the basic concepts and learn some basic ways of doing what you are trying to achieve. Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM