Search code examples
mongodbmongodb-stitch

Mongodb Stitch realtime watch


What I intend to achieve is some sort of "live query" functionality. So far I've tried using the "watch" method. According to the documentation:

You can open a stream of changes that match a filter by calling collection.watch(delegate:) with a $match expression as the argument. Whenever the watched collection changes and the ChangeEvent matches the provided $match expression, the stream’s event handler fires with the ChangeEvent object as its only argument

Passing the doc ids as an array works perfectly, but passing a query doesn't work:

this.stitch.db.collection<Queue>('queues')
                        .watch({
                          hospitalId: this.activehospitalid
                         }));

I've also tried this:

this.stitch.db.collection<Queue>('queues')
                        .watch({
                           $match: {
                              hospitalId: this.activehospitalid
                              }
                            },
                          ));

Which throws an error on the console "StitchServiceError: mongodb watch: filter is invalid (unknown top level operator: $match)". The intention is watch all documents where the field "hospitalId" matches the provided value, or to effectively pass a query filter to the watch() method.


Solution

  • After a long search I found that it's possible to filter, but the query needs to be formatted differently

    this.stitch.db.collection<Queue>('queues')
                            .watch({
                               $or: [
                                     {
                                       "fullDocument.hospitalId": this.activehospitalid
                                     }
                                    ]
                                },
                              ));
    

    For anyone else who might need this, please note the important fullDocument part of the query. I havent found much documentation relating to this, but I hope it helps