mongoose-plugin-events

[![npm version](https://img.shields.io/npm/v/mongoose-plugin-events.svg)](https://www.npmjs.com/package/mongoose-plugin-events) [![license](https://img.shields.io/github/license/mgcrea/mongoose-plugin-events.svg?style=flat)](https://tldrlegal.com/license/

Usage no npm install needed!

<script type="module">
  import mongoosePluginEvents from 'https://cdn.skypack.dev/mongoose-plugin-events';
</script>

README

mongoose-plugin-events

npm version license build status dependencies status devDependencies status Codacy Badge npm downloads

React on database changes with document and models events

Note

  • v2.x for mongoose@^5
  • v1.x for mongoose@^4

Quickstart

  • Load the plugin inside your schema
import {Schema} from 'mongoose';
import eventsPlugin from 'mongoose-plugin-events';

const schema = new Schema({
  name: {type: String, required: true},
  content: {type: Object, default: {}}
});

// Add events
schema.plugin(eventsPlugin, {});

export default schema;
  • Listen on document events
const Device = mongoose.model('Device');
Device.on('created', ({_id}) => {
  log.info('Detected device="%s" creation', _id);
})
  • Listen for field scoped events
const Device = mongoose.model('Device');
Device.on('updated:lastSeen', ({query, operator, update}) => {
  const deviceId = update._id;
  log.info('Detected device="%s" lastSeen update', deviceId);
});
  • Listen on schema events (eg. other plugins):
schema.on('model:updated', ({query, update}, model) => {
  const updateActivities = [];
  if (update.name) {
    updateActivities.push(castUpdateActivity({
      code: ACTIVITY_CODES.DEVICE_RENAMED,
      context: {name: update.name}
    }));
  }
  if (updateActivities.length) {
    model.trackActivities(updateActivities);
  }
});

schema.on('model:removed', (doc, model) => {
  model.trackActivity({
    code: ACTIVITY_CODES.DEVICE_DELETED,
    context: {},
    target: doc._id,
    targetRef: 'Device',
    source: doc.removedBy,
    sourceRef: 'User'
  });
});

Testing

  • You can quickly start hacking around
git clone -o github git@github.com:mgcrea/mongoose-plugin-events.git
cd mongoose-plugin-events
npm i
npm test