mongoose-monitor-fields-plugin

monitor and respond to changes in your documents!

Usage no npm install needed!

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

README

mongoose-monitor-fields-plugin

build status code coverage code style styled with prettier made with lass license npm downloads

monitor and respond to changes in your documents!

Table of Contents

Install

npm:

npm install mongoose-monitor-fields-plugin

yarn:

yarn add mongoose-monitor-fields-plugin

Basic Example Usage

const { Schema } = require('mongoose');
const monitorFields = require('mongoose-monitor-fields-plugin');

const mySchema = new Schema({
  my_field: {
    type: String,
    // set monitor true to have the change passed to the document level callback post save
    // or define a function for a field level callback post save
    monitor: console.log
  }
});

mySchema.plugin(monitorFields, console.log);

const MyModel = model('MySchema', mySchema);

(async () => {
  let myDocument = new MyModel({
    my_field: 'foo'
  });
  await myDocument.save();
  myDocument.my_field = 'bar';
  await myDocument.save();

  // prints the following to the console
  // for the field level callback
  // {path: 'my_field', prev: 'foo', updated: 'bar'}
  // for the document level
  // [{path: 'my_field', prev: 'foo', updated: 'bar'}]
})();

In either field level or document level callbacks - this refers to the newly updated document.

Special Credit

This package was heavily influenced by mongoose-plugin-diff

Contributors

Name Website
Spencer Snyder https://spencersnyder.io

License

MIT © Spencer Snyder