Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Implementation of MongoDB Changestream

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

I think you need to update the pipeline as well

private readonly pipeline = [
  {
    $match: {
      $or: [
        { operationType: 'insert' },
        { operationType: 'update' }, // Match update operations
      ],
    },
  },
];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading