All Projects → eoin-obrien → Mongoose Update If Current

eoin-obrien / Mongoose Update If Current

Licence: mit
Optimistic concurrency (OCC) plugin for mongoose.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Mongoose Update If Current

Mevn Cli
Light speed setup for MEVN(Mongo Express Vue Node) Apps
Stars: ✭ 696 (+1040.98%)
Mutual labels:  mongoose, npm-package
express-mvc-generator
Express' Model View Controller Application Generator.
Stars: ✭ 46 (-24.59%)
Mutual labels:  mongoose, npm-package
Fclub
Vue全家桶+Koa+mongoose全栈开发的单页应用 http://wap.fulun.club
Stars: ✭ 49 (-19.67%)
Mutual labels:  mongoose
Mongoose Fill
Virtual async fileds for mongoose.js
Stars: ✭ 57 (-6.56%)
Mutual labels:  mongoose
Alfred Lock
Alfred 3 workflow to lock your Mac
Stars: ✭ 54 (-11.48%)
Mutual labels:  npm-package
Node Env Webpack Plugin
Simplified `NODE_ENV` handling with webpack
Stars: ✭ 51 (-16.39%)
Mutual labels:  npm-package
Gulp Wxa Copy Npm
微信小程序gulp插件,解决npm包管理和babel-runtime
Stars: ✭ 55 (-9.84%)
Mutual labels:  npm-package
Slugify Cli
Slugify a string
Stars: ✭ 49 (-19.67%)
Mutual labels:  npm-package
Cli Mandelbrot
📦 View the Mandelbrot set from your terminal
Stars: ✭ 59 (-3.28%)
Mutual labels:  npm-package
Vue Element Responsive Demo
基于 Vue + Element 的响应式后台模板
Stars: ✭ 54 (-11.48%)
Mutual labels:  mongoose
String Hash
Get the hash of a string
Stars: ✭ 56 (-8.2%)
Mutual labels:  npm-package
Cdfang Spider
📊 成都房协网数据分析,喜欢请点 star!
Stars: ✭ 1,063 (+1642.62%)
Mutual labels:  mongoose
Node Native Ext Loader
Loader for Node native extensions
Stars: ✭ 51 (-16.39%)
Mutual labels:  npm-package
Node React Ecommerce
Build ECommerce Website Like Amazon By React & Node & MongoDB
Stars: ✭ 1,080 (+1670.49%)
Mutual labels:  mongoose
Awesome Node Utils
some useful npm packages for nodejs itself
Stars: ✭ 51 (-16.39%)
Mutual labels:  npm-package
Rest Hapi
🚀 A RESTful API generator for Node.js
Stars: ✭ 1,102 (+1706.56%)
Mutual labels:  mongoose
Nodereactionagent
NodeReactionAgent is an Node.js asynchronous performance monitoring tool to be in conjunction with Nodereaction.com or nodereactionclient
Stars: ✭ 49 (-19.67%)
Mutual labels:  npm-package
Mongomem
In-memory MongoDB Server. Ideal for testing.
Stars: ✭ 51 (-16.39%)
Mutual labels:  mongoose
Capture Website
Capture screenshots of websites
Stars: ✭ 1,075 (+1662.3%)
Mutual labels:  npm-package
Packagephobia
⚖️ Find the cost of adding a new dependency to your project
Stars: ✭ 1,110 (+1719.67%)
Mutual labels:  npm-package

mongoose-update-if-current

Build Status Version Dependencies DevDependencies Maintainability Test Coverage Greenkeeper Status Dependabot Status

Optimistic concurrency control plugin for Mongoose v5.0 and higher.

This plugin brings optimistic concurrency control to Mongoose documents by incrementing document version numbers on each save, and preventing previous versions of a document from being saved over the current version.

Inspired by issue #4004 in the Mongoose GitHub repository.

Installation

$ npm install --save mongoose
$ npm install --save mongoose-update-if-current

Getting Started

Import the plugin from the package:

/* Using ES2015 imports */
import { updateIfCurrentPlugin } from 'mongoose-update-if-current';

/* Using require() */
const { updateIfCurrentPlugin } = require('mongoose-update-if-current');

Add it to mongoose as a global plugin, or add it to a single schema:

/* Global plugin */
mongoose.plugin(updateIfCurrentPlugin);

/* Single schema */
const mySchema = new mongoose.Schema({ ... });
mySchema.plugin(updateIfCurrentPlugin);

Default behaviour is to use the schema's version key (__v by default) to implement concurrency control. The plugin can be configured to use timestamps (updatedAt by default) instead, if they are enabled on the schema:

/* Global plugin - remember to add { timestamps: true } to each schema */
mongoose.plugin(updateIfCurrentPlugin, { strategy: 'timestamp' });

/* Single schema */
const mySchema = new mongoose.Schema({ ... }, { timestamps: true });
mySchema.plugin(updateIfCurrentPlugin, { strategy: 'timestamp' });

The plugin will hook into the save() function on schema documents to increment the version and check that it matches the version in the database before persisting it.

NB: If the schema has a custom version key or timestamp field set, then the plugin will automatically regognise and use it. An error will be throws if you attempt to add the plugin to a schema without the fields to support it.

Usage

Let's save a new Book to MongoDB.

    // Save a new Book document to the database
    let book = await new Book({
        title: 'The Prince',
        author: 'Niccolò Machiavelli',
    }).save();

Our book document should look something like this:

    {
        __v: 0,
        title: 'The Prince',
        author: 'Niccolò Machiavelli',
        ...
    }

Now that it's in the database, a user fetches the book and updates it.

    let book = await Book.findOne({ title: 'The Prince' });
    book.title = 'Il Principe';
    book = await book.save();

The book document in MongoDB now looks like this:

    {
        __v: 1,  // note the incremented version
        title: 'Il Principe',
        author: 'Niccolò Machiavelli',
        ...
    }

Meanwhile, another user tries to update the book, fetching it before it was updated.

    // Before the call to save() above, so book.__v is 0
    let book = await Book.findOne({ title: 'The Prince' });
    // Now the other user updates the book, so our version is out of date
    // Try to update the book based on the stale version
    book.author = 'Niccolò di Bernardo dei Machiavelli';
    book = await book.save();  // throws a VersionError

When the other user tries to save an out-of-date version of the document to the database, the operation fails and throws an error.

NB: The plugin throws a VersionError when in { strategy: 'version' } mode, but throws a DocumentNotFoundError when in { strategy: 'timestamp' } mode.

See the __tests__ directory for more usage examples.

Notes

  • The plugin manages concurrency when a document is updated using Document.save(), but you can still force updates using Model.update(), Model.findByIdAndUpdate() or Model.findOneAndUpdate() if you so desire.
  • The plugin relies on either __v or updatedAt to implement concurrency control; as such, this plugin might not be compatible with other plugins that alter these fields.
  • The plugin causes the document's version to be incremented whenever save() is called when using it for concurrency control.

Development

The project uses the Google JavaScript code style. The test suites are built on Facebook's Jest. Make sure that any changes you make are fully tested and linted before submitting a pull request!

Command Description
npm test Runs tests
npm run build Builds the project
npm run ci Builds the project, runs tests and reports coverage
npm run clean Cleans build output directories
npm run babel Transpiles JavaScript code
npm run lint Lints JavaScript code

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].