Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am using express and MongoDB and want some real-time updates whenever any change happens in my DB. I use MongoDB change stream. But when I put my change function inside the route it only sends a response when I hit my route, and when I put the change function outside of the route I am unable to send a response.

So my problem how to send a response when any change happens in my collection.

const testSchema = new Schema({
  name: { type: String, required: true },
  email: { type: String, required: true },
});

const model = mongoose.model('test', testSchema);

//change 
model.watch().on('change', (data) => {
  console.log(data);
});

router.put('/update', async (req, res) => {
  const data = req.body;
  const info = await model.updateOne(data);
  res.send(info);
});


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
162 views
Welcome To Ask or Share your Answers For Others

1 Answer

Whats you're trying to achieve relies on Web socket.
Sockets are the way in which you can make applications communicate across network.

Your browser uses socket programming. It establishes a connection with the server on port 80(only for HTTP requests) and gets data from the server and displays it according to the markup.

If you had played any online games like, Counter-Strike for example, where you had been a host then you would have understood its usage. You establish yourself as a host with certain port allocated to communicate. The game then passes data using that socket to other computers.

You'll have to learn and understand SocketIO to achieve this.

Most of the lessons out there are being explained how it can be used for chat applications. But if you understand it better, you'll be able to build anything upon socket.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...