Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get fullDocumentBeforeChange from MongoDB Change Streams in NodeJS with Mongoose?

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.

like image 231
Dev M Avatar asked Sep 20 '25 12:09

Dev M


2 Answers

I switched to MongoDB 6.0.3 and I run the command:

db.runCommand ( { collMod: "myCollection", changeStreamPreAndPostImages: { enabled: true } } );
like image 97
Dev M Avatar answered Sep 23 '25 02:09

Dev M


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.

like image 38
FiveOFive Avatar answered Sep 23 '25 02:09

FiveOFive