Home > Net >  Database insert data, real-time render to frontend
Database insert data, real-time render to frontend

Time:11-08

The idea is that the sensor in water will send data to my database, and I want the data to be sent to the frontend in real-time, in other words: Database update and then frontend update.

The tools I use:

  1. MongoDB
  2. NodeJS
  3. Socket io
  4. ReactJS

It works fine actually and here is my main code to handle real-time data flow

const Zips = require("./dataSchema");

io.on("connection", (socket) => {
    setInterval(()=>{
         Zips.find().then((result) => {
    socket.emit("output", result);
  });
    }, 5000)
});

#Zips is schema use mongoose
I use setinterval to update every 5 seconds.

Question :

does Socket-io or Mongodb provide any function or method so that doesn't need setInterval or any other way?

##edit 11/8 the ray show the documentation works.

CodePudding user response:

solution :

io.on("connection",(socket)=>{
  const changeStream = Zips.watch()
  changeStream.on('change',(next)=>{
    if(next.operationType=="insert"){
      Zips.find().then((result) => {
           socket.emit("output", result);
        });
    }
  })
})

using watch(), and then the callback function provides a lot of data can track with.
documentation : change streams

  • Related