DEV Community

GreggHume
GreggHume

Posted on • Updated on

MongoDB: How to get fullDocument from changeStream when a document is deleted

In order to get the full document in a watcher after deleting the document you need to enable collMod on the collection. See the below 4 steps.

1.Download mongoshell https://www.mongodb.com/try/download/shell

2.Run mongoshell and paste your connection string with an admin user and press enter (create a temporary admin if you need to) Looks like this:

mongodb+srv://user:QkKvrDtL0yZFERGA@showspace-cluster.1yyql9v.mongodb.net/my-db`
Enter fullscreen mode Exit fullscreen mode

3.In mongoshell run the following command to change the 'collMod' for your collection - swop out my collection 'ProductReview' for your collection

db.runCommand({collMod: "ProductReview", changeStreamPreAndPostImages: {enabled: true}})
Enter fullscreen mode Exit fullscreen mode

4.Now in your app you can setup a change stream and access the deleted document like so (the below code is nodejs)

const client = new MongoClient(env.DATABASE_URL);
const database = client.db("my_database");
const reviews = database.collection("ProductReview");

// 'fullDocumentBeforeChange' is the magic here
const changeStream = reviews.watch([], { 
  fullDocument: "updateLookup", 
  fullDocumentBeforeChange: "required" 
});

changeStream.on("change", async (event) => {
  let document;

  if (event.operationType === 'delete') {
    document = event.fullDocumentBeforeChange;
  } else {
    document = event.fullDocument;
  }

  // do some stuff with the document
});   
Enter fullscreen mode Exit fullscreen mode

Documentation:
https://www.mongodb.com/docs/v6.0/reference/operator/aggregation/changeStream/

Related questions:

Top comments (0)