NestJS-Mongoose: cannot access fullDocument on ChangeEvent<any>

Viewed 572

I have the following basic snippet of code and my aim is to get the fullDocument property from the obj: ChangeEvent however I am not able to access this property (Property 'fullDocument' does not exist on type 'ChangeEvent<any>'). The only properties I can access are _id, clusterTime and operationType. Is there something I am missing or should I just query the fullDocument non-directly (obj['fullDocument'])?

const changeStream = this.model.watch([], { fullDocument: 'updateLookup' })
      .on('change', obj => {
        console.log(obj.fullDocument);
      });
1 Answers

The problem you're having (TypeScript complaining about the missing property) is due to unspecialized return type generic mongodb.ChangeStream in mongoose's Model.watch method (in both @types/mongoose and official mongoose types, I'm assuming you are using mongoose 5.x branch).

For example @types/mongodb package declares/specializes the return type on the watch method correctly.

The real solution would be to create a Pull Request fixing the return type of the watch return type in the aforementioned package repositories, and/or report the issue to maintainers. For a quick 'fix' you could resort to type casting like this (for the cleanest changeStream shape the MySchema should be the class you've annotated with @Schema):

const changeStream = this.model
  .watch([], { fullDocument: 'updateLookup' }) as ChangeStream<MySchema>; // <-- specialize using the cast
      
changeStream.on('change', obj => {
  console.log(obj.fullDocument);
});

Also be aware that MongoDB Change Stream requires Replica Set or Sharded Cluster.

Related