Nodejs checking if resumeToken exists in oplog

I am using changeStreams to listen for changes of some collections, so i can replicate these changes to another database.
I save the changeStream _id as a resumeToken, and each time a changeStream comes in, i update the resume token.

const changeStream = db.watch({ fullDocument: 'updateLookup' }, { resumeAfter: token });
changeStream.on('change', async next => {
// Code
}

How do i check if that resumeToken is valid or exists in main database?

2 Likes

You can have the connection in a try-catch block and try to access the changeStream and if that throws an error, in the catch block you can connect to the changeStream without resume token.

try {
await mongoCollection.watch(, {
fullDocument,
startAfter: token,
})?.tryNext();
changeStream = mongoCollection.watch(, {
fullDocument,
startAfter: token,
});

} catch (error) {
changeStream = mongoCollection.watch();
}