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
I changed the filter to:
Calling
.collection
is unnecessary. You can call.watch
directly on your model. E.g.,To capture all insert operations, and any updates where name or message are updated, adjust your filter: