watch() API
Overview
watch() returns the MongoDB driver's native ChangeStream<T> object. Use it when you want direct driver-level event handling. If you need persisted resume tokens, multi-target fanout, idempotency markers, and lifecycle stats, use ChangeStreamSyncManager.
Basic usage
API Reference
collection.watch([pipeline], [options])
Monitor collection data changes.
Parameters:
pipeline(Array, optional): aggregation pipeline for filtering eventsoptions(Object, optional): Configuration options
Return value: ChangeStream<TSchema> — MongoDB driver native ChangeStream object
⚠️
collection.watch()directly returns the MongoDB drivenChangeStreamwithout additional packaging. Please refer to MongoDB ChangeStream official documentation.
Configuration options
MongoDB native options
ChangeStream native method
watch() returns the MongoDB-driven ChangeStream<T> object, which supports the following native APIs:
cs.on(event, handler)
Listen for events (EventEmitter interface).
Event List:
'change': Data change'error': Error'close': Close'end': end of stream
cs.once(event, handler)
Listen for events (one-time).
cs.close()
Close ChangeStream.
Return value: Promise<void>
cs.closed
Read-only property that checks whether the ChangeStream has been closed.
Type: boolean
cs.resumeToken
Read-only attribute, obtains the latest resumeToken (used for resumed transmission).
Type: unknown
cs.next()
Explicitly get the next change event (iterator pattern).
Return value: Promise<ChangeStreamDocument<T>>
💡 If you want resume-token persistence, multi-target synchronization, and lifecycle stats for supervised restarts, use
ChangeStreamSyncManager.
Usage example
Example 1: Basic monitoring
Example 2: Filter events
Example 3: Error handling
Example 4: Statistics monitoring (via ChangeStreamSyncManager)
For built-in statistics (eventCount / syncedCount / errorCount), please use
ChangeStreamSyncManager:
Example 5: Graceful shutdown
Cache invalidation integration
⚠️
collection.watch()itself does not provide built-in cache invalidation function. If you want to integrate watch with cache, there are two options:
Solution 1: Manual processing (lightweight scenario recommended)
Solution 2: ChangeStreamSyncManager (recommended for production scenarios)
ChangeStreamSyncManager has built-in breakpoint resumption, multi-target synchronization and statistical capabilities, and can handle caching in the apply callback:
Cross-instance cache invalidation: use the Cache API with cache.distributed configured, then follow the deployment notes in Distributed Deployment.
Notes
1. MongoDB version requirements
Change Streams requires MongoDB 4.0+ and a replica set or sharded cluster environment.
Single node environment will report an error:
Solution:
Dev/Test Environment - using mongodb-memory-server:
useMemoryServer uses a single-node replica set, the binary cache is pinned at .cache/mongodb-memory-server/binaries, and the automatically created temporary dbPath is pinned at .cache/mongodb-memory-server/db and cleaned up on shutdown.
Production environment - using replica sets or sharded clusters:
2. Performance impact
- watch itself has little impact on performance (natively supported by MongoDB)
- ChangeStream monitoring is asynchronous and does not block the main process
3. resumeToken expires
The MongoDB oplog has a size limit and the resumeToken may expire (default hours).
Handling Suggestions:
- Monitor
errorevents and detectChangeStreamHistoryLosterrors - Close the current ChangeStream and call
collection.watch()again (withoutresumeAfter) - If you need to automatically handle breakpoint resumption, please use
ChangeStreamSyncManager
4. Memory management
Long-running watches need to pay attention to:
- Correctly call
watcher.close()to release resources - Listening process signal is closed gracefully
- Don’t create too many watchers (1-2 per collection is enough)
Troubleshooting
Problem 1: watch closes immediately
Reason: MongoDB is not a replica set environment
Solution: Use replica set or mongodb-memory-server
Issue 2: ChangeStream closed unexpectedly
Cause: If the network is unstable or MongoDB load is too high, ChangeStream will automatically shut down and trigger the close event.
Troubleshooting:
Question 3: Cache integration
See the Cache Invalidation Integration chapter.
watch event vs global event
Difference description
monSQLize has two event systems:
1. Global event (msq object):
- Monitoring object: query operation of the application
- Event type:
slow-query,query,connected,error,closed - Applicable scenarios: performance monitoring, operation and maintenance alarms
- Document: Event System
2. watch event (ChangeStream object):
- Monitoring object: MongoDB data changes
- Event types:
change,error,close,end(MongoDB native events) - Applicable scenarios: real-time data synchronization, cache invalidation
- Documentation: This document
Usage scenario comparison
Example: Use both
Related documents
- MongoDB Change Streams official documentation
- Distributed Deployment Guide
- Caching System
- Event System