简体   繁体   English

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

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

I'm using react js for building frontend for a website.我正在使用 react js 为网站构建前端。 An express server (which is a microservice) sits in between the front end and MongoDB.一个快速服务器(它是一个微服务)位于前端和 MongoDB 之间。 I make Axios calls from react js to express server (URL = http://localhost:5688/chat ) using GET, POST, PUT whenever and wherever needed.我随时随地使用 GET、POST、PUT 从 react js 调用 Axios 到 express 服务器(URL = http://localhost:5688/chat )。

something like below像下面的东西

Client side客户端

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

Server side服务器端

app.js应用程序.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');
});

Above is how I've implemented a GET call.以上是我实现 GET 调用的方式。 Similarly, I've implemented POST and PUT methods as well.同样,我也实现了 POST 和 PUT 方法。

PS: I removed a lot of intermediate code which is not very helpful for this question PS:我删除了很多对这个问题没有太大帮助的中间代码

Now I want to use MongoDB change stream to listen to all changes that happen to my collection on MongoDB.现在我想使用MongoDB 更改 stream来收听我在 MongoDB 上的集合发生的所有更改。 I'm aware of the tutorials that show how we can log the updated documents in the express server.....such as this tutorial .我知道教程展示了我们如何在快速服务器中记录更新的文档......例如本教程 This makes it possible for my express server to get all the updated documents whenever data in my DB is changed.这使得我的快速服务器可以在我的数据库中的数据发生更改时获取所有更新的文档。

But what I'm not sure about is how I can pass this new data to my client so that I can update my react component's state with this new data.但我不确定如何将这些新数据传递给我的客户端,以便我可以用这些新数据更新我的反应组件的 state。

How do I make my frontend code sitting in my browser continuously listen to my express server (a REST API) which is already continuously listening to all changes in MongoDB with the help of change streams?如何让位于浏览器中的前端代码持续监听我的快速服务器(REST API),该服务器已经在更改流的帮助下不断监听 MongoDB 中的所有更改?

Is socket the only way to make my client continuously listen to my server?套接字是让我的客户端持续监听我的服务器的唯一方法吗? if so, how would I pass the new data coming from MongoDB streaming to the socket on the express server如果是这样,我将如何将来自 MongoDB 流的新数据传递到快速服务器上的套接字

Please let me know if I should provide more details.请让我知道我是否应该提供更多详细信息。 Thank you so much.太感谢了。

Is socket the only way to make my client listen to my server?套接字是让我的客户端监听我的服务器的唯一方法吗?

Well, yes.嗯,是。 a socket connection is the only way you'll have to use something like socket.io or other socket implementation to do so.套接字连接是您必须使用类似socket.io或其他套接字实现的唯一方法。

However nodejs concept is the opposite of maintaining socket connections as that can become expensive when your connections amount scale up.然而nodejs的概念与维护socket连接相反,因为当您的连接量增加时,这可能会变得昂贵。

I feel the better more reliable solution is to ask the server every x seconds (2-3?) "has changes been made" and if so update the view.我觉得更好更可靠的解决方案是每x秒(2-3?)询问服务器“是否已进行更改”,如果是,请更新视图。

With that said, depending on the exact state your saving on your app this might be not viable as a solution.话虽如此,根据确切的 state 您在应用程序上的节省,这可能不是可行的解决方案。

I will give you an example from my own project in production:我会给你一个我自己的生产项目的例子:

//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

});


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM