paralect/node-mongo

Watching changes

Opened this issue · 4 comments

Hi all,

I am wondering would this allow me to watch for for a changes (Event Handlers section) and trigger something?
I've setup simple query which works just fine, but event has never been triggered when data in DB is changed

userService.on('updated', ({ doc, prevDoc }) => { console.log("Here we go, change!")});

Would this supposed to work if I update any record?

Thanks!

Hi, @markosole, you are right, it should work.

I suppose you used the atomic method for updating that doesn't trigger events.
To trigger an event you need to use this method userService.updateOne()

Oh okey, I've used MongoDB Compas to update data. Does this watch changes in DB or service itself?
How does it actually watch for changes? - I haven't setup any replication or multiple servers, what's required for "normal" mongoose Watch() to work. Thanks!

I am having problem with "Listening to events on the Db class has been deplecated". I know it's not really related to this subject but relevant. This is my package dependecies list

"dependencies": {
    "@paralect/node-mongo": "^2.1.1",
    "body-parser": "^1.19.1",
    "dotenv": "^10.0.0",
    "mongodb": "^4.2.1",
    "mongodb-topology-manager": "^2.1.0",
    "mongoose": "^6.1.1",
    "monk": "^7.3.4",
    "mysql": "^2.18.1",
    "node-ray": "^1.17.0",
    "nodemon": "^2.0.15",
}

I've found that there is "monk" problem with versions. Any idea how to fix this?

@markosole

Unfortunately, monk does not support the modern version of mongodb driver, we started removing monk but #49 is still in progress, I suppose I will continue to work on this PR in the near future.

Watching on changes works only when using updatedOn method, because this method also makes a comparison between current and new documents, and emits 'updated' event.
you can check its implementation https://github.com/paralect/node-mongo/blob/master/src/mongo-service.js#L170

So it will not work if you will use Robo3T or MongoDB Atlas or atomic methods.

We don't use Change Streams because it doesn't return the previous document.
But when it will we will migrate to Change Streams, so events will be triggered from anywhere (atomic methods, Atlas, Robo3T)

Thanks for clarification, I think I will switch to socket method with self made solution.