Connection.prototype.watch()

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

Watches the entire underlying database for changes. Similar to Model.watch().

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 User = conn.model('User', new Schema({ name: String }));
  2. const changeStream = conn.watch().on('change', data => console.log(data));
  3. // Triggers a 'change' event on the change stream.
  4. await User.create({ name: 'test' });