Introduction
Resume tokens help you continue reading data from where you left off without missing or repeating anything.
const changeStream = collection.watch([], { resumeAfter: resumeToken });const changeStream = collection.watch();const changeStream = collection.watch([], { resumeAfter: lastResumeToken });changeStream.on('change', (change) => {
lastResumeToken = change._id;
});const { MongoClient } = require('mongodb'); async function watchWithResume() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const db = client.db('testdb'); const collection = db.collection('testcol'); let resumeToken = null; // Start watching changes const changeStream = collection.watch([], resumeToken ? { resumeAfter: resumeToken } : {}); changeStream.on('change', (change) => { console.log('Change detected:', change); resumeToken = change._id; // Save token to resume later }); // Simulate running for 10 seconds setTimeout(async () => { await changeStream.close(); await client.close(); console.log('Stopped watching changes.'); }, 10000); } watchWithResume();
resumeAfter to resume from a token.startAfter, continueFrom, and restartFrom are not valid MongoDB options.const changeStream = collection.watch([], { resumeAfter: savedToken });
changeStream.on('change', (change) => {
console.log(change._id);
});resumeAfter option tells MongoDB to start the change stream from the event after the saved token._id of each change event starting after the saved token.resumeAfter on restart ensures continuous, reliable watching.Pass the test and this pattern moves unknown