NestJS-Mongoose: cannot access fullDocument on ChangeEvent<any>
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.