Search code examples
node.jsmongodbmongoose

How to watch for changes to some fields in MongoDB change streams?


I'm using Mongoose and MongoDB and Nodejs and I want to listen for changes to some fields and also if there is insert operations in a MongoDB collection.

Here, I want to display event if name or message changes. If I set filter = [] I get every update.

The actual result: the console log event display only update operations.

const mongoose = require('mongoose');
const myModel = require('../models/myModel');

const getConnection = async (callback, io) => {
try {
    await mongoose.connect(process.env.DATABASE, {}).then(() => {}).catch((error) => {});
    const filter = [{
        $match: {
            $or: [
                { "updateDescription.updatedFields.name": { $exists: true } },
                { "updateDescription.updatedFields.message": { $exists: true } }
            ]
        }
    }];

    const options = { fullDocument: 'updateLookup', fullDocumentBeforeChange: 'whenAvailable' };
    myModel.collection('myCollection').watch(filter, options).on('change', async  (event) => 
    {
        console.log('event:', event);
    });
 } catch (error) {
   console.log('error', error);
 }
}

Solution

  • I changed the filter to:

    const filter = [
            {
              $match: {
                $or: [
                  {
                    'updateDescription.updatedFields.name': { $exists: true }
                  },
                  { 'updateDescription.updatedFields.message': { $exists: true } },
                  { operationType: 'insert' },
                  { operationType: 'update' }
                ]
              }
            }
          ];