http://mongodb.github.io/node-mongodb-native/3.1/api/ChangeStream.html according to this document, the next function must return null if no exist anymore document but for me not working.
this is my code :
while (await changeStreamIterator.hasNext()) {
let change = await changeStreamIterator.next();
if (change == null)
console.log("end");
}
Hello @Pejman_Azad, welcome to the MongoDB Community forum.
Within the while loop, in the statement let change = await changeStreamIterator.next();
the variable change
has a Change Event document.
The loop waits until there is a change in the collection (or database or the deployment). The change event document will have the info about the change (i.e., about the update on the collection).
For example:
There is a collection called mycoll
and as I do insert, update or modify operations on it, the change stream on the collection will notify the changes:
const database = client.db("test");
const collection = database.collection("coll");
const changeStream = collection.watch();
while (await changeStream.hasNext()) {
let change = await changeStream.next();
if (change == null) console.log("event doc was null!!");
console.log(change); // notified change event document
}
When a document is inserted/updated/deleted in the mycoll
the change event document is printed. For example, a delete generates this change document:
{
_id: {
_data: '825FFED...D986AE41A80004'
},
operationType: 'delete',
clusterTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1610536524 },
ns: { db: 'test', coll: 'mycoll' },
documentKey: { _id: 5ffed280937038d986ae41a8 }
}
In case of a condition where the change event document cannot be generated then there will be a null
- I suspect it might be some kind of error or abnormal condition (I coudn’t find any documentation on this).
Meanwhile the change stream cursor remains open until one of these occur - the cursor is explicitly closed or an invalidate event occurs - and then exists the loop.