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:
- MongoDB
- NodeJS
- Socket io
- 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