skip to Main Content

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);
 }
}

2

Answers


  1. Chosen as BEST ANSWER

    I changed the filter to:

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

  2. Calling .collection is unnecessary. You can call .watch directly on your model. E.g.,

    myModel
      .watch(filter, options)
      .on("change", async (event) => {
          console.log("event:", event);
      });
    

    To capture all insert operations, and any updates where name or message are updated, adjust your filter:

      const filter = [
        {
          $match: {
            $or: [
              // log all insert operations
              { operationType: "insert" },
              // log updates to name or message
              { "updateDescription.updatedFields.name": { $exists: true } },
              { "updateDescription.updatedFields.message": { $exists: true } }
            ],
          },
        },
      ];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search