如何通过 REST API 微服务(使用 Express 构建)使用 MongoDB 使用节点 js 更改流

How to use MongoDB change streams with node js via a REST API microservice (built with Express)

我正在使用 React js 为网站构建前端。一个快速服务器(这是一个微服务)位于前端和 MongoDB 之间。我随时随地使用 GET、POST、PUT 从 React js 调用 Axios 来表达服务器(URL = http://localhost:5688/chat)。

如下所示

客户端

var resp = axios.get(`http://localhost:5688/chat`);
resp.then((response) => {
this.setState({data: response.data})
})

服务器端

app.js

var app = express();

app.get('/chat', function (req, res) {
    try {
        var MongoClient = require('mongodb').MongoClient;
        var url = '***********';
        MongoClient.connect(url, { useUnifiedTopology: true }, function(err, client) {
             if (err){
                console.log('error occured while connection to databse ' + err);
             }
             else{
                db.collection(collectionName).find({}).toArray(function(err, result){
                    if (err) {throw err;}
                    else{
                        client.close();
                        res.join(result); // the result would contain the data fetch from db and will be returned to my axios call
                    }
                });
            }
        });
    }
    catch (ex) {
        res.json(ex);
    }
});

app.listen(5688, function(){
    console.log('Server listening at http://localhost:5688');
});

以上是我实现 GET 调用的方式。同样,我也实现了 POST 和 PUT 方法。

PS: 我删除了很多对这道题帮助不大的中间代码

现在我想使用MongoDB change stream to listen to all changes that happen to my collection on MongoDB. I'm aware of the tutorials that show how we can log the updated documents in the express server.....such as this tutorial。这使得我的快速服务器可以在我的数据库中的数据发生更改时获取所有更新的文档。

但我不确定如何将此新数据传递给我的客户端,以便我可以使用此新数据更新我的 React 组件的状态。

如何让我的前端代码在我的浏览器中持续监听我的快速服务器(一个 REST API),它已经在 change 的帮助下连续监听 MongoDB 中的所有变化流?

套接字是让我的客户端持续监听我的服务器的唯一方法吗?如果是这样,我如何将来自 MongoDB 流的新数据传递到快速服务器

上的套接字

如果我需要提供更多详细信息,请告诉我。非常感谢。

Is socket the only way to make my client listen to my server?

嗯,是的。套接字连接是您必须使用类似 socket.io 或其他套接字实现的唯一方法。

然而,nodejs 概念与维护 socket 连接相反,因为当您的连接数量增加时,维护连接会变得昂贵。

我觉得更好更可靠的解决方案是每 x 秒(2-3 秒?)"has changes been made" 询问服务器,如果是这样更新视图。

话虽如此,根据您在应用程序中保存的确切状态,这可能无法作为解决方案。

我会给你一个我自己的生产项目的例子:

//Server-side

//Assume tweetDB is the DB 
//Assume you have socket.io setup

//MongoDB Change Stream
const changeStream = tweetDB.watch();


changeStream.on('change', (changes) => {

//Add a event emitter
            socket.compress(true).emit('mongoStream',changes);

        });


//Client-side in a js file or a script tag
//Assuming you have established a WebSocket connection already

//Add an event listener to listen for back end changes. 

socket.on('mongoStream',data=>{
console.log(data)

});

//Note: Socket.io is event-driven.

//Add an event emitter
socket.emit('eventName','dataToEmit');

//Add an event listener
socket.on('eventName',data=>{

//Process the data here

});