Real-time Data with Change Streams
Utilize MongoDB's change streams to monitor and react to changes in real-time RAG statuses, ensuring data is immediately updated and retrieved without poling.
<div id='status-container'></div>
HTML structure to display RAG (Red, Amber, Green) statuses. This div will be dynamically updated with the status information.
#status-container {
padding: 10px;
border: 1px solid #ccc;
margin-bottom: 10px;
}
.status-item {
border-bottom: 1px solid #eee;
padding: 5px 0;
}
CSS styles for the status container and individual status items.
const statusContainer = document.getElementById('status-container');
// Function to render status to the DOMunction updateStatusOnUI(data) {
const statusElement = document.createElement('div');
statusElement.classList.add('status-item');
statusElement.textContent = `Status: ${data.status} - Message: ${data.message}`;
statusContainer.appendChild(statusElement);
}
JavaScript function to update the UI with a new status item.
const MongoClient = require('mongodb').MongoClient;
const uri = 'YOUR_MONGODB_CONNECTION_STRING';
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db('test').collection('devices');
const changeStream = collection.watch();
changeStream.on('change', (change) => {
if (change.operationType === 'insert' || change.operationType === 'update') {
const statusData = change.fullDocument;
updateStatusOnUI(statusData);
}
});
});
Setup MongoDB change streams in a Node.js environment. Replace YOUR_MONGODB_CONNECTION_STRING with your actual connection string. Also, replace 'test' and 'devices' with your database and collection names. This code sets up a listener for changes (inserts and updates) and updates the web page with the new status using the 'updateStatusOnUI' function.