I'm using Mongoose and MongoDB and Nodejs and I want to listen for changes to a MongoDB collection and console log the document before change and the update description.
The actual result: I can only log the update description.
const didChangeStream = model.collection.watch({
fullDocument: 'updateLookup',
fullDocumentBeforeChange: 'whenAvailable'
});
didChangeStreamAlert.on('change', async (event) => {
const {
documentKey,
fullDocument,
fullDocumentBeforeChange,
updateDescription
} = event;
console.log('fullDocumentBeforeChange', fullDocumentBeforeChange);
console.log('updateDescription', updateDescription);
});
I switch to mongoDB v6.0.3 and I tried to enable the changeStreamPreAndPostImages for myCollection using:
db.runCommand ( { collMod: "myCollection", changeStreamPreAndPostImages: { enabled: false } } );
{ ok: 1, '$clusterTime': { clusterTime: Timestamp({ t: 1671719738, i: 1 }), signature: { hash: Binary(Buffer.from("0000000000000000000000000000000000000000", "hex"), 0), keyId: Long("0") } }, operationTime: Timestamp({ t: 1671719738, i: 1 }) }
the db.runCommand worked for me but in nodejs the fullDocumentBeforeChange is null.
In mongoDB v5, the fullDocumentBeforeChange is not displayed and in mongoDB v6 fullDocumentBeforeChange is null.
I switched to MongoDB 6.0.3 and I run the command:
db.runCommand ( { collMod: "myCollection", changeStreamPreAndPostImages: { enabled: true } } );
You can enable changeStreamPreAndPostImages
in the mongoose Schema via collectionOptions
new Schema({}, { collectionOptions: { changeStreamPreAndPostImages: { enabled: true } } })
Note that this creates the collection with changeStreamPreAndPostImages enabled, but it does not update an existing collection.
Alternatively, you can use the mongo createCollection
or collMod
commands to enable changeStreamPreAndPostImages
outside of mongoose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With