How to control change stream output using Mongoose

63 Views Asked by At

I am trying Mongodb change streams using Mongoose:

Person.watch().on('change', data => console.log(data));

It tracked all the change of the database, is it possible to apply condition and track certain documents instead, like how to check id==1 and id==2 documents only?

1

There are 1 best solutions below

2
Fourchette On

I'm not sure if you can do this on the model. But assuming you can, you probably can pass a pipeline to filter the input docs. I personnaly use watch on the DB and it works fine.

Here, i use the {fullDocument:"updateLookup"} option to add the whole object to results. I can then match the id with simple $in query operator.

Person.watch( [
      {
        $match: {
          "fullDocument.id": {"$in" : [1,2]},       
        },
      },
    ],
    {
      fullDocument: "updateLookup",
    }).on('change', data => console.log(data));