I am facing some issues while implementing changestream of mongodb in nestJS. Here is the code
export class UsersService {
constructor(
@InjectModel('User')
private userModel: Model<User>,
) {}
private changeStream: ChangeStream;
private readonly pipeline = [
{
$match: {
operationType: 'insert',
},
},
];
async onModuleInit() {
console.log('inside module init');
await this.startChangeStream();
}
async startChangeStream() {
this.changeStream = this.userModel.watch(this.pipeline, {
fullDocument: 'updateLookup',
});
this.changeStream.on('change', async ({ fullDocument }: any) => {
console.log('Change:', fullDocument);
})
async updateUser(updateUserDTO: UpdateUserDTO) {
//logic
}
}
I am using updateUser method of UsersService to update name of the user. The name gets updated but the changestream does not get triggered.
What am I doing wrong here?
I tried shifting code from here and there, event tried providing this as module through app module but it didn't work. I'm expecting this changestream to work.
I think you need to update the pipeline as well
private readonly pipeline = [
{
$match: {
$or: [
{ operationType: 'insert' },
{ operationType: 'update' }, // Match update operations
],
},
},
];