Model.watch()

Parameters
Returns:
  • «ChangeStream» mongoose-specific change stream wrapper, inherits from EventEmitter

Requires a replica set running MongoDB >= 3.6.0. Watches the underlying collection for changes using MongoDB change streams.

This function does not trigger any middleware. In particular, it does not trigger aggregate middleware.

The ChangeStream object is an event emitter that emits the following events

  • ‘change’: A change occurred, see below example
  • ‘error’: An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow this GitHub issue for updates.
  • ‘end’: Emitted if the underlying stream is closed
  • ‘close’: Emitted if the underlying stream is closed

Example:

  1. const doc = await Person.create({ name: 'Ned Stark' });
  2. const changeStream = Person.watch().on('change', change => console.log(change));
  3. // Will print from the above `console.log()`:
  4. // { _id: { _data: ... },
  5. // operationType: 'delete',
  6. // ns: { db: 'mydb', coll: 'Person' },
  7. // documentKey: { _id: 5a51b125c5500f5aa094c7bd } }
  8. await doc.remove();