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);
});