Drinkler
Drinkler

Reputation: 71

How to update html without reloading the page every time I get a new database entry

I am setting up a node.js server which constantly checks a mongo database for new entries. If a new entry comes the html site should get updated without a reload and with the data from the database.

I can already receive the data every time a new entry is made, but I can't update the site. I looked up some possible tools like ajax or react.js but I just don't find the perfect solution (or even a solution) of how this could work.

Connection to Mongodb and receiving the data

MongoClient.connect('mongodb://192.168.128.128:27017/familientag', function(err, client) {
  if (err) {
    console.error('An error occurred connecting to MongoDB: ', err);
  } else {
    const db = client.db("familientag")
    const collection = db.collection('data');
    console.log("Connected successfully to server");

    const changeStream = collection.watch();
    changeStream.on('change', next => {
      console.log(next.fullDocument['name']);
      // Here I receive the data "_id" and "name"
    });
  }
});

My index.ejs

<!DOCTYPE html>
<html>
    <head>
        <title>Dies ist ein Test</title>
    </head>
    <body>
        <div id="target">
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script>
            $.ajax({
                type: 'GET',
                url: '/test',
                success: function(data) {
                    var html = data;
                    $('#target').html(html);
                }
            });
        </script>
    </body>
</html>

call index

app.get('/index', function (req, res) {
  res.render('index');
});

I expect to see the name on the index site everytime a new dataset has been read from the db without reloading the window.

Upvotes: 1

Views: 1524

Answers (1)

Sam Smith
Sam Smith

Reputation: 99

Using an open socket should help you out. You can either pass the new data into the socket body, or simply trigger the UI to request the data from an api.

I'd recommend taking a look at socket.io: https://socket.io/ to get going very quickly. It's a flexible socket framework for node with brilliant docs.

Pusher is a great option if you want to manage less of the socket state yourself. Comes with its own UI. https://pusher.com/

Upvotes: 2

Related Questions