Git Product home page Git Product logo

mongoose-patch-history's Introduction

npm version Build Status Greenkeeper badge Known Vulnerabilities Coverage Status

Mongoose Patch History is a mongoose plugin that saves a history of JSON Patch operations for all documents belonging to a schema in an associated "patches" collection.

Installation

$ npm install mongoose-patch-history

Usage

To use mongoose-patch-history for an existing mongoose schema you can simply plug it in. As an example, the following schema definition defines a Post schema, and uses mongoose-patch-history with default options:

import mongoose, { Schema } from 'mongoose'
import patchHistory from 'mongoose-patch-history'

/* or the following if not running your app with babel:
const patchHistory = require('mongoose-patch-history').default;
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
*/

const PostSchema = new Schema({
  title: { type: String, required: true },
  comments: Array,
})

PostSchema.plugin(patchHistory, { mongoose, name: 'postPatches' })
const Post = mongoose.model('Post', PostSchema)

mongoose-patch-history will define a schema that has a ref field containing the ObjectId of the original document, a ops array containing all json patch operations and a date field storing the date where the patch was applied.

Storing a new document

Continuing the previous example, a new patch is added to the associated patch collection whenever a new post is added to the posts collection:

Post.create({ title: 'JSON patches' })
  .then(post => post.patches.findOne({ ref: post.id }))
  .then(console.log)

// {
//   _id: ObjectId('4edd40c86762e0fb12000003'),
//   ref: ObjectId('4edd40c86762e0fb12000004'),
//   ops: [
//     { value: 'JSON patches', path: '/title', op: 'add' },
//     { value: [], path: '/comments', op: 'add' }
//   ],
//   date: new Date(1462360838107),
//   __v: 0
// }

Updating an existing document

mongoose-patch-history also adds a static field Patches to the model that can be used to access the patch model associated with the model, for example to query all patches of a document. Whenever a post is edited, a new patch that reflects the update operation is added to the associated patch collection:

const data = {
  title: 'JSON patches with mongoose',
  comments: [{ message: 'Wow! Such Mongoose! Very NoSQL!' }],
}

Post.create({ title: 'JSON patches' })
  .then(post => post.set(data).save())
  .then(post => post.patches.find({ ref: post.id }))
  .then(console.log)

// [{
//   _id: ObjectId('4edd40c86762e0fb12000003'),
//   ref: ObjectId('4edd40c86762e0fb12000004'),
//   ops: [
//     { value: 'JSON patches', path: '/title', op: 'add' },
//     { value: [], path: '/comments', op: 'add' }
//   ],
//   date: new Date(1462360838107),
//   __v: 0
// }, {
//   _id: ObjectId('4edd40c86762e0fb12000005'),
//   ref: ObjectId('4edd40c86762e0fb12000004'),
//   ops: [
//     { value: { message: 'Wow! Such Mongoose! Very NoSQL!' }, path: '/comments/0', op: 'add' },
//     { value: 'JSON patches with mongoose', path: '/title', op: 'replace' }
//   ],
//   "date": new Date(1462361848742),
//   "__v": 0
// }]

Rollback to a specific patch

rollback(ObjectId, data, save)

Documents have a rollback method that accepts the ObjectId of a patch doc and sets the document to the state of that patch, adding a new patch to the history.

Post.create({ title: 'First version' })
  .then(post => post.set({ title: 'Second version' }).save())
  .then(post => post.set({ title: 'Third version' }).save())
  .then(post => {
    return post.patches
      .find({ ref: post.id })
      .then(patches => post.rollback(patches[1].id))
  })
  .then(console.log)

// {
//   _id: ObjectId('4edd40c86762e0fb12000006'),
//   title: 'Second version',
//   __v: 0
// }

Injecting data

Further the rollback method accepts a data object which is injected into the document.

post.rollback(patches[1].id, { name: 'merged' })

// {
//   _id: ObjectId('4edd40c86762e0fb12000006'),
//   title: 'Second version',
//   name: 'merged',
//   __v: 0
// }

Rollback without saving

To rollback the document to a specific patch but without saving it back to the database call the method with an empty data object and the save flag set to false.

post.rollback(patches[1].id, {}, false)

// Returns the document without saving it back to the db.
// {
//   _id: ObjectId('4edd40c86762e0fb12000006'),
//   title: 'Second version',
//   __v: 0
// }

The rollback method will throw an Error when invoked with an ObjectId that is

  • not a patch of the document
  • the latest patch of the document

Options

PostSchema.plugin(patchHistory, {
  mongoose,
  name: 'postPatches',
})
  • mongoose πŸ“Œ required
    The mongoose instance to work with
  • name πŸ“Œ required
    String where the names of both patch model and patch collection are generated from. By default, model name is the pascalized version and collection name is an undercore separated version
  • removePatches
    Removes patches when origin document is removed. Default: true
  • transforms
    An array of two functions that generate model and collection name based on the name option. Default: An array of humps.pascalize and humps.decamelize
  • includes
    Property definitions that will be included in the patch schema. Read more about includes in the next chapter of the documentation. Default: {}
  • excludes
    Property paths that will be excluded in patches. Read more about excludes in the excludes chapter of the documentation. Default: []
  • trackOriginalValue
    If enabled, the original value will be stored in the change patches under the attribute originalValue. Default: false

Includes

PostSchema.plugin(patchHistory, {
  mongoose,
  name: 'postPatches',
  includes: {
    title: { type: String, required: true },
  },
})

This will add a title property to the patch schema. All options that are available in mongoose's schema property definitions such as required, default or index can be used.

Post.create({ title: 'Included in every patch' })
  .then((post) => post.patches.findOne({ ref: post.id })
  .then((patch) => {
    console.log(patch.title) // 'Included in every patch'
  })

The value of the patch documents properties is read from the versioned documents property of the same name.

Reading from virtuals

There is an additional option that allows storing information in the patch documents that is not stored in the versioned documents. To do so, you can use a combination of virtual type setters on the versioned document and an additional from property in the include options of mongoose-patch-history:

// save user as _user in versioned documents
PostSchema.virtual('user').set(function (user) {
  this._user = user
})

// read user from _user in patch documents
PostSchema.plugin(patchHistory, {
  mongoose,
  name: 'postPatches',
  includes: {
    user: { type: Schema.Types.ObjectId, required: true, from: '_user' },
  },
})

// create post, pass in user information
Post.create({
  title: 'Why is hiring broken?',
  user: mongoose.Types.ObjectId(),
})
  .then(post => {
    console.log(post.user) // undefined
    return post.patches.findOne({ ref: post.id })
  })
  .then(patch => {
    console.log(patch.user) // 4edd40c86762e0fb12000012
  })

In case of a rollback in this scenario, the rollback method accepts an object as its second parameter where additional data can be injected:

Post.create({ title: 'v1', user: mongoose.Types.ObjectId() })
  .then(post =>
    post
      .set({
        title: 'v2',
        user: mongoose.Types.ObjectId(),
      })
      .save()
  )
  .then(post => {
    return post.patches.find({ ref: post.id }).then(patches =>
      post.rollback(patches[0].id, {
        user: mongoose.Types.ObjectId(),
      })
    )
  })

Reading from query options

In situations where you are running Mongoose queries directly instead of via a document, you can specify the extra fields in the query options:

Post.findOneAndUpdate(
  { _id: '4edd40c86762e0fb12000012' },
  { title: 'Why is hiring broken? (updated)' },
  { _user: mongoose.Types.ObjectId() }
)

Excludes

PostSchema.plugin(patchHistory, {
  mongoose,
  name: 'postPatches',
  excludes: [
    '/path/to/hidden/property',
    '/path/into/array/*/property',
    '/path/to/one/array/1/element',
  ],
})

// Properties
// /path/to/hidden:                   included
// /path/to/hidden/property:          excluded
// /path/to/hidden/property/nesting:  excluded

// Array element properties
// /path/into/array/0:                included
// /path/into/array/345345/property:  excluded
// /path/to/one/array/0/element:      included
// /path/to/one/array/1/element:      excluded

This will exclude the given properties and all nested paths. Excluding / however will not work, since then you can just disable the plugin.

  • If a property is {} or undefined after processing all excludes statements, it will not be included in the patch.
  • Arrays work a little different. Since json-patch-operations work on the array index, array elements that are {} or undefined are still added to the patch. This brings support for later remove or replace operations to work as intended.
    The ARRAY_WILDCARD * matches every array element.

If there are any bugs experienced with the excludes feature please write an issue so we can fix it!

mongoose-patch-history's People

Contributors

bloodhawk avatar codepunkt avatar compwright avatar danielbayerlein avatar dependabot[bot] avatar greenkeeper[bot] avatar jtlindsey avatar mbaertschi avatar snyk-bot avatar vinerich avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongoose-patch-history's Issues

An in-range update of mongoose is breaking the build 🚨

The dependency mongoose was updated from 5.2.17 to 5.2.18.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

mongoose is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Commits

The new version differs by 16 commits.

  • 3084fcb chore: release 5.2.18
  • b844bca style: fix lint re: #5704
  • 53c39fa fix(populate): handle multiple localFields + foreignFields using localField: function() {} syntax
  • 0e2d638 test(populate): repro #5704
  • 55ad233 docs(aggregate): fix syntax highlighting on allowDiskUse() docs
  • 7c2eb93 docs(migrating_to_5): add note about overwriting filter properties
  • 9975182 fix(document): retain user-defined key order on initial set with nested docs
  • fd8e227 test(document): repro #6944
  • 8fea4f8 fix(query): correctly handle select('+c') if c is not in schema
  • 5ec10b6 test(query): repro #7017
  • 477e8ca test(model): add coverage for #6972
  • 05aa04d fix(document): check path exists before checking for required
  • 2221d72 chore: hide home page ad on mobile
  • b54ce42 style fix some more lint warnings
  • eedfc03 chore: now working on 5.2.18

There are 16 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

mongoose 6.4.4 not work

when use mongoose 6.4.4 show this error:
also I make connection with createConnection and I pass mongoose: myConnection in option

schema = schema._clone(this.base.Schema);
                      ^
TypeError: schema._clone is not a function
    at NativeConnection.Connection.model (D:\Projects\Tests\node-ts-sample-decorator2\node_modules\mongoose\lib\connection.js:1186:23)
    at createPatchModel (D:\Projects\Tests\node-ts-sample-decorator2\node_modules\mongoose-patch-history\lib\index.js:343:27)
    at exports.default (D:\Projects\Tests\node-ts-sample-decorator2\node_modules\mongoose-patch-history\lib\index.js:85:17)
    at Schema.plugin (D:\Projects\Tests\node-ts-sample-decorator2\node_modules\mongoose\lib\schema.js:1738:3)
    at _buildSchema (D:\Projects\Tests\node-ts-sample-decorator2\node_modules\@typegoose\typegoose\src\internal\schema.ts:162:13)
    at buildSchema (D:\Projects\Tests\node-ts-sample-decorator2\node_modules\@typegoose\typegoose\src\typegoose.ts:167:21)
    at getModelForClass (D:\Projects\Tests\node-ts-sample-decorator2\node_modules\@typegoose\typegoose\src\typegoose.ts:89:58)
    at src/services/member/member.model.ts (D:\Projects\Tests\node-ts-sample-decorator2\src\src\services\member\member.model.ts:95:39)
    at __require (D:\Projects\Tests\node-ts-sample-decorator2\src\index.ts:11:50)
    at src/services/member/member.resolver.ts (D:\Projects\Tests\node-ts-sample-decorator2\src\src\services\member\member.resolver.ts:27:24)
    at __require (D:\Projects\Tests\node-ts-sample-decorator2\src\index.ts:11:50)
    at Object.<anonymous> (D:\Projects\Tests\node-ts-sample-decorator2\src\import-glob:.\services\**\*.resolver.ts:2:34)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Module._compile (D:\Projects\Tests\node-ts-sample-decorator2\node_modules\source-map-support\source-map-support.js:547:25)
    at Module.mod._compile (D:\Projects\Tests\node-ts-sample-decorator2\node_modules\esbuild-runner-plugins\src\hook.ts:25:22)
    at Module._extensions..js (internal/modules/cjs/loader.js:1114:10)

Mongoose .update and .findByIdAndUpdate seems to not trigger 'patching'

Hello,

As the title say, i can only get the plugin to work when i, like the doc, do a Model.find() , then, on the found document, do a .set().save() .
I'm a begginner so i might be wrong, but is this a Mongoose limitations? I found this bit in the Mongoose doc:

Although values are casted to their appropriate types when using update, the following are not applied:

defaults
setters
validators
middleware
If you need those features, use the traditional approach of first retrieving the document.

Is this the reason?

Bug: With the plugin, updateOne hangs, if nothing was found

If nothing was found with updateOne, (same for update and updateMany) query just hangs without response.

When I turn off the plugin, I get correct result from the query:
{ n: 0, nModified: 0, ok: 1 }

versions:
node: 14.11.0
mongodb: 3.6.2
mongoose: 5.10.6
mongoose-patch-history: the version from github master

config:

Schema.plugin(patchHistory, {
  mongoose, name: 'ModelPatches', trackOriginalValue: true, removePatches: false
})

Is this repo still active?

Hey together,

I'd like to use this plugin in a current project. At the moment I got the issue that the Fix null pointer commit 450c5eb is not included in the latest release.
I could work around that with only using the save() function but that wouldn't be my first priority.

So I'm asking if you will find the time to make another release or if one can help out and fix the outstanding problems to make the release as easy as possible for you.

schema.s.hooks.createWrapperSync is not a function

So, I had an error first, which was
Error: First param to `schema.plugin()` must be a function, got "object"

Adding .default like: const patchHistory = require('mongoose-patch-history').default; did the trick for me.

Now, I am getting that error, and I am not sure how to handle it.

TypeError: schema.s.hooks.createWrapperSync is not a function                                                                      
    at applyHooks (E:\Info\localhost\Web Development\NodeJS\autotash\node_modules\mongoose\lib\services\model\applyHooks.js:50:5)  
    at Function.compile (E:\Info\localhost\Web Development\NodeJS\autotash\node_modules\mongoose\lib\model.js:3782:3)              
    at Mongoose.model (E:\Info\localhost\Web Development\NodeJS\autotash\node_modules\mongoose\lib\index.js:381:22)                
    at createPatchModel (E:\Info\localhost\Web Development\NodeJS\autotash\node_modules\mongoose-patch-history\lib\index.js:284:27)
    at exports.default (E:\Info\localhost\Web Development\NodeJS\autotash\node_modules\mongoose-patch-history\lib\index.js:73:17)  
    at Schema.plugin (E:\Info\localhost\Web Development\NodeJS\autotash\node_modules\mongoose\lib\schema.js:1129:3)                
    at Object.<anonymous> (E:\Info\localhost\Web Development\NodeJS\autotash\modules\requests\requests.model.js:55:15)             
    at Module._compile (module.js:635:30)                                                                                          
    at Object.Module._extensions..js (module.js:646:10)                                                                            
    at Module.load (module.js:554:32)                                                                                              
    at tryModuleLoad (module.js:497:12)                                                                                            
    at Function.Module._load (module.js:489:3)                                                                                     
    at Module.require (module.js:579:17)                                                                                           
    at require (internal/module.js:11:18)                                                                                          
    at Object.<anonymous> (E:\Info\localhost\Web Development\NodeJS\autotash\initilize\globalFuns.js:25:33)                        
    at Module._compile (module.js:635:30)                                                                                          
    at Object.Module._extensions..js (module.js:646:10)                                                                            
    at Module.load (module.js:554:32)                                                                                              
    at tryModuleLoad (module.js:497:12)                                                                                            
    at Function.Module._load (module.js:489:3)                                                                                     
    at Module.require (module.js:579:17)                                                                                           
    at require (internal/module.js:11:18)                                                                                          

An in-range update of mongoose is breaking the build 🚨

The dependency mongoose was updated from 5.6.8 to 5.6.9.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

mongoose is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Commits

The new version differs by 19 commits.

  • 188b4e7 chore: release 5.6.9
  • 347eeeb chore: add papersowl as sponsor
  • 379a807 style: fix lint
  • 4a84546 fix(schema): fix test failures from previous fix of #8034
  • 6149ba3 docs(index): add dcsl as sponsor
  • f47e936 fix(schema): allow declaring ObjectId array with { type: 'ObjectID' }, last 'D' case insensitive
  • bc71f25 test(schema): repro #8034
  • ad41e38 Merge branch 'master' of github.com:Automattic/mongoose
  • 9023f30 docs(guide): add missing further reading link and link to other tutorial
  • 419cfef Merge pull request #8048 from Fonger/fix/version-error-memory-leak
  • 612c4f9 chore: now working on 5.6.9
  • 4408e55 fix(cursor): correctly handle batchSize option with query cursor
  • eff168d test(query): repro #8039
  • b850278 fix(populate): handle virtual populate with count = 0 if virtual embedded in doc array
  • 548ab98 test(populate): repro #7573 part 2

There are 19 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Timeout upon saving a new document

I'm new to document versioning and have been trialing on a few similar plugins. It may be my mis-configuration, but I have really no idea what's going wrong after attempting for a whole day...

When I comment out the plugin-related script, Mongoose works as expected. But if the plugin is applied, new document cannot be saved and results in timeout...

Debug: handler, error
    Error: Operation `issue_patches.insertOne()` buffering timed out after 10000ms        
    at Toolkit.badRequest (...\microservice-issue\lib\boom.js:43:34)
    at handler (...\microservice-issue\lib\controllers\issue.js:95:16)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

Below is my models/issue.js.

'use strict'

const Mongoose = require('mongoose')
// const History = require('mongoose-patch-history').default

const issueSchema = new Mongoose.Schema({
  trelloId: String,
  trelloUrl: String,
  parcelNo: String,
  warehouse: String,
  courier: String,
  issueReason: Number,
  photo: [{
    url: String,
    remark: String
  }],
  status: {
    type: String,
    default: 'To Do'
  },
  updatedBy: String
})

// issueSchema.plugin(History, {
//   mongoose: Mongoose,
//   name: 'issuePatches'
// })

module.exports = {
  name: 'Issue',
  schema: issueSchema
}

Versions:
node: 12.18.4
mongodb: 4.2.11
mongoose: 5.11.4
mongoose-patch-history: 2.0.0

Appreciate any help. Thank you!

Possible documentation inconsistency

In "Storing a new document" section, an operation for '/comments' is shown. I'm not sure if this would really be generated without the comments field having a default of empty array.

// {
//   _id: ObjectId('4edd40c86762e0fb12000003'),
//   ref: ObjectId('4edd40c86762e0fb12000004'),
//   ops: [
//     { value: 'JSON patches', path: '/title', op: 'add' },
//     { value: [], path: '/comments', op: 'add' }
//   ],
//   date: new Date(1462360838107),
//   __v: 0
// }

Support for String type Document._id

If you use a String or non ObjectId type value for document._id, you get a CastError:

CastError: Cast to ObjectId failed for value "645e40b4-3dbd-45ce-a27e-3122401f592e" at path "ref" for model "myModelHistory"

When performing:

Model.findOne({ ... })
    .then(function(document) {
        return document.patches.find({
            ref: document._id
        })
    })

Example Schema:

const Schema = new mongoose.Schema({
    _id: {
        type: String,
        default: app._.uuid.v4
    },
    title: {
        type: String
    }
})

Resulting document from plugin:

{
    "_id" : ObjectId("59320cc7ed01f374e3563007"),
    "ops" : [ 
        {
            "value" : "New Title",
            "path" : "/title",
            "op" : "replace"
        }
    ],
    "date" : ISODate("2017-06-03T01:11:35.886Z"),
    "__v" : 0
}

Should be a simple fix, I'll checkout the source and hopefully have a PR soon.

Adding lean() causes TypeError: document.data is not a function

Tested with https://github.com/codepunkt/mongoose-patch-history#b9d8abde29d0b1df5137f8c4565a73069aeff3d0

Perhaps this cannot be supported and should be mentioned in the README?

    it('with findOneAndUpdate upsert', (done) => {
      Post.findOneAndUpdate(
        { title: 'findOneAndUpdateUpsert' },
        { $set: { title: 'findOneAndUpdateUpsert' } },
        {
          new: true,
          upsert: true,
          setDefaultsOnInsert: true,
          runValidators: true
        }
      )
        .lean()
        .then((post) =>
          post.patches
            .find({ ref: post._id })
            .sort({ _id: 1 })
            .then((patches) => {
              assert.equal(patches.length, 1)
            })
        )
        .then(done)
        .catch(done)
    })

Some troubles with virtual path

Servus,
while trying to get the plugin to work I had a few issues, most of them were lack of understanding on my end, so it isn't that much of a biggie, but I thought I'd post it here in case someone else runs into the issue.

At first I had this:

(function (exports, require, module, __filename, __dirname) { import patchHistory from 'mongoose-patch-history';
SyntaxError: Unexpected identifier

Probably my settings, had to use require instead and when calling the plugin I had to make sure I used
computerSchema.plugin(patchHistory.default, { mongoose, name: 'computerHist' });

Then I had this:

\node_modules\mongoose\lib\schema.js:1601
    throw new Error('Virtual path "' + name + '"' +
Error: Virtual path "patches" conflicts with a real path in the schema

I'm unsure as to that path "patches" being used, I don't really have an overview of all the things that are going on in the project, so I changed this line a bit:

var Patches = createPatchModel(options);
  schema.statics.Patches = Patches;
  schema.virtual('patches_hist').get(function () {
    return Patches;
  });

Working like a charm afterwards, maybe the name "patches" is a bit too generic, thanks for the awesome work!

Too many patches when saving refs?

I have two schemas defined as follows:

I have two schemas defined as follows.

const PersonSchema = new mongoose.Schema({
  organization: {
    type: mongoose.Schema.Types.ObjectId,
    ref: ORGANIZATION_MODEL_NAME,
    required: true,
  },
  name: {
    type: String,
    unique: true,
    required: true,
  }
})

const OrganizationSchema = new mongoose.Schema({
  name: {
    type: String,
    unique: true,
    required: true,
  }
})

I can create a person, no problem.

Organization
  .create({ name: 'Home '})
  .then((org) => Person.create({ name: 'Bob', organization: organization._id })
  .then((person) => {
    // Now I have `person`
  });

However, if I try to change the org on the person:

person.set({ organization: 'MY_NEW_ID' }).save();

Patches looks like this:

DATE/OP/PATH/VALUE
2017-02-10T06:26:29.312Z  replace /organization/id/10 231 
2017-02-10T06:26:29.312Z  replace /organization/id/9  108 
2017-02-10T06:26:29.312Z  replace /organization/id/8  82  
2017-02-10T06:26:29.312Z  replace /organization/id/7  24  
2017-02-10T06:26:29.312Z  replace /organization/id/6  9 
2017-02-10T06:26:29.312Z  replace /organization/id/5  211 
2017-02-10T06:26:29.312Z  replace /organization/id/4  12  
2017-02-10T06:26:29.312Z  replace /organization/id/3  234 
2017-02-10T06:26:29.312Z  replace /organization/id/2  74

I was expecting more something like:

DATE/OP/PATH/VALUE
2017-02-10T06:26:29.312Z  replace /organization/id/2  MY_NEW_ID

Am I doing something wrong?

An in-range update of mongoose is breaking the build 🚨

The dependency mongoose was updated from 5.4.13 to 5.4.14.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

mongoose is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Commits

The new version differs by 18 commits.

  • 35b90d2 chore: release 5.4.14
  • 8dc47a5 docs(schema): add examples for remaining functions
  • 764735b fix(documentarray): report validation errors that occur in an array subdoc created using create() and then set()
  • 3fec456 test(documentarray): repro #7504
  • 660fe60 chore: remove unnecessary print statements
  • 13c7a00 docs(schema): add examples to schema functions
  • 270732e docs(migrating_to_5): link to migrating to 5 docs on the mongoosejs.com website
  • db79cfc Merge branch 'master' of github.com:Automattic/mongoose
  • 67754bd style: fix lint
  • 8e30004 Merge pull request #7530 from sarpik/master
  • 3e44bc2 Merge branch 'master' of github.com:Automattic/mongoose
  • aa43200 docs: add MongooseError to API docs and add list of error names
  • 0daf626 Merge pull request #7521 from nocksapp/master
  • 8752502 fix anchor tag
  • b5f1723 chore: now working on 5.4.14

There are 18 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Not capturing delete events.

If I am deleting the original document it's not capturing that. Tried using both 'fine' and 'deleteOne' syntax.

  return await ppc.deleteOne({ _id: id });
  return await ppc.find({ _id: id }).remove();

Cannot perform an `add` operation at the desired path

NodeJS: 12.16.3
npm: 6.14.4
OS: ubuntu

I'm trying to read the initial patch record with help of rollback but it is throwing an error like,

Cannot perform an `add` operation at the desired path
name: OPERATION_PATH_CANNOT_ADD

doc = await doc.rollback(patches[0]._id.toString(), {}, false);

How do I read read the initial (operation: { op: 'add', ...) record?

Breaking change in new released version v1.4.0: MongoError: unknown top level operator: $push

Hi Team

Thanks for the new release of this module.

I have however picked an issue which has caused a breaking change to occur. It seems that the $push operation is no longer supported with the new changes introduced. Within your test script you have a test which should verify this but it doesnt seem to be working in a real world scenario.

I have created a basic gist of the files and steps needed to reproduce the error. I have made use of your actual test file in the master branch and removed the unrelated sections for this issue (Only testing the $push related operation).
https://gist.github.com/BMartinos/d24dab6cb6d5b77600a5aeb990c0d40f

The error being returned when executing the reproducible test script can be seen below:

Error:  { MongoError: unknown top level operator: $push
    at MessageStream.messageHandler (/../mongoose-patch-history-test/node_modules/mongodb/lib/cmap/connection.js:266:20)
    at MessageStream.emit (events.js:198:13)
    at processIncomingData (/../mongoose-patch-history-test/node_modules/mongodb/lib/cmap/message_stream.js:144:12)
    at MessageStream._write (/../mongoose-patch-history-test/node_modules/mongodb/lib/cmap/message_stream.js:42:5)
    at doWrite (_stream_writable.js:415:12)
    at writeOrBuffer (_stream_writable.js:399:5)
    at MessageStream.Writable.write (_stream_writable.js:299:11)
    at Socket.ondata (_stream_readable.js:710:20)
    at Socket.emit (events.js:198:13)
    at addChunk (_stream_readable.js:288:12)
    at readableAddChunk (_stream_readable.js:269:11)
    at Socket.Readable.push (_stream_readable.js:224:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17) ok: 0, code: 2, codeName: 'BadValue', name: 'MongoError' }

An in-range update of bluebird is breaking the build 🚨

The devDependency bluebird was updated from 3.5.2 to 3.5.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

bluebird is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v3.5.3

Bugfixes:

  • Update acorn dependency
Commits

The new version differs by 7 commits.

  • a5a5b57 Release v3.5.3
  • c8a7714 update packagelock
  • 8a765fd Update getting-started.md (#1561)
  • f541801 deps: update acorn and add acorn-walk (#1560)
  • 247e512 Update promise.each.md (#1555)
  • e2756e5 fixed browser cdn links (#1554)
  • 7cfa9f7 Changed expected behaviour when promisifying (#1545)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

All of a sudden started to get an error saying TypeError: Cannot set property '_original' of null

Everything seems to work well. But all of a sudden I got the following error:

TypeError: Cannot set property '_original' of null
    at /Users/pubudu/Projects/FleetManager/fm-main-api/node_modules/mongoose-patch-history/lib/index.js:191:21

Unfortunately, I was unable to find the exact issue.

This is how I attached it to my model:

EquipmentSchema.plugin(patchHistory, {
  mongoose,
  name: 'equipmentHistory'
});

I also tried setting trackOriginalValue: false but still it did not work. Any idea what's happening?

Cannot read property '$__' of undefined

Hello,

Thanks for making this module. It looks like exactly what I was looking for but I'm having trouble getting it to work. I'm trying to add it to a existing model in a app that has no problems without the module. The app does not have a babel dependency so i'm using require instead of import. Can anyone point out what I'm missing?

Here is example model:

const patchHistory = require('mongoose-patch-history').default;
const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const Purchase = new Schema(
  {
    company: { type: String, trim: true, default: '' },
    refFile: [{ type: Schema.Types.ObjectId, ref: 'File' }],
    status: {
      type: String,
      enum: ['New', 'Old'],
      default: 'New',
    },
    updatedBy: { type: Schema.Types.ObjectId, ref: 'User' },
  },
  {
    timestamps:
      true,
  },
);

Purchase.plugin(patchHistory, { 
  mongoose, 
  name: 'purchasePatches',
  includes: {
    company: { type: String, required: true }
  },
});

module.exports = mongoose.model('Purchase', Purchase);

My error when saving new record

file error TypeError: Cannot read property '$__' of undefined
    at cleanModifiedSubpaths (/home/test/test_api/node_modules/mongoose-patch-history/node_modules/mongoose/lib/helpers/document/cleanModifiedSubpaths.js:12:46)
    at Array._registerAtomic (/home/test/test_api/node_modules/mongoose-patch-history/node_modules/mongoose/lib/types/array.js:182:7)
    at model.Document.$__set (/home/test/test_api/node_modules/mongoose/lib/document.js:894:11)
    at model.$set (/home/test/test_api/node_modules/mongoose/lib/document.js:780:10)
    at model._handleIndex (/home/test/test_api/node_modules/mongoose/lib/document.js:596:14)
    at model.$set (/home/test/test_api/node_modules/mongoose/lib/document.js:556:24)
    at model.Document (/home/test/test_api/node_modules/mongoose/lib/document.js:85:12)
    at model.Model (/home/test/test_api/node_modules/mongoose/lib/model.js:56:12)
    at new model (/home/test/test_api/node_modules/mongoose/lib/model.js:3939:13)
    at /home/test/test_api/node_modules/mongoose/lib/model.js:2080:22
    at /home/test/test_api/node_modules/async/internal/parallel.js:31:39
    at eachOfArrayLike (/home/test/test_api/node_modules/async/eachOf.js:65:9)
    at exports.default (/home/test/test_api/node_modules/async/eachOf.js:9:5)
    at _parallel (/home/test/test_api/node_modules/async/internal/parallel.js:30:5)
    at parallelLimit (/home/test/test_api/node_modules/async/parallel.js:88:26)
    at /home/test/test_api/node_modules/mongoose/lib/model.js:2096:5
    at new Promise (<anonymous>)
    at Function.create (/home/test/test_api/node_modules/mongoose/lib/model.js:2051:17)
    at createPatch (/home/test/test_api/node_modules/mongoose-patch-history/lib/index.js:138:29)
    at model.<anonymous> (/home/test/test_api/node_modules/mongoose-patch-history/lib/index.js:142:5)
    at _next (/home/test/test_api/node_modules/hooks-fixed/hooks.js:63:32)
    at fnWrapper (/home/test/test_api/node_modules/hooks-fixed/hooks.js:190:8)

My error on edit (using findByIdAndUpdate)

UnhandledPromiseRejectionWarning: TypeError: Cannot read property '$__' of undefined
    at cleanModifiedSubpaths (/home/test/test_api/node_modules/mongoose-patch-history/node_modules/mongoose/lib/helpers/document/cleanModifiedSubpaths.js:12:46)
    at Array._registerAtomic (/home/test/test_api/node_modules/mongoose-patch-history/node_modules/mongoose/lib/types/array.js:182:7)
    at model.Document.$__set (/home/test/test_api/node_modules/mongoose/lib/document.js:894:11)
    at model.$set (/home/test/test_api/node_modules/mongoose/lib/document.js:780:10)
    at model._handleIndex (/home/test/test_api/node_modules/mongoose/lib/document.js:596:14)
    at model.$set (/home/test/test_api/node_modules/mongoose/lib/document.js:556:24)
    at model.Document (/home/test/test_api/node_modules/mongoose/lib/document.js:85:12)
    at model.Model (/home/test/test_api/node_modules/mongoose/lib/model.js:56:12)
    at new model (/home/test/test_api/node_modules/mongoose/lib/model.js:3939:13)
    at /home/test/test_api/node_modules/mongoose/lib/model.js:2080:22
    at /home/test/test_api/node_modules/async/internal/parallel.js:31:39
    at eachOfArrayLike (/home/test/test_api/node_modules/async/eachOf.js:65:9)
    at exports.default (/home/test/test_api/node_modules/async/eachOf.js:9:5)
    at _parallel (/home/test/test_api/node_modules/async/internal/parallel.js:30:5)
    at parallelLimit (/home/test/test_api/node_modules/async/parallel.js:88:26)
    at /home/test/test_api/node_modules/mongoose/lib/model.js:2096:5
    at new Promise (<anonymous>)
    at Function.create (/home/test/test_api/node_modules/mongoose/lib/model.js:2051:17)
    at createPatch (/home/test/test_api/node_modules/mongoose-patch-history/lib/index.js:138:29)
    at /home/test/test_api/node_modules/mongoose-patch-history/lib/index.js:192:14
    at processTicksAndRejections (internal/process/next_tick.js:81:5)

Stack:

// Node 11.12.0   
// npm 6.7.0   
// MongoDB 3.4.16   

$ npm list mongoose
β”œβ”€β”€ [email protected] 
└─┬ [email protected]
  └── [email protected]

An in-range update of fast-json-patch is breaking the build 🚨

The dependency fast-json-patch was updated from 2.0.7 to 2.1.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

fast-json-patch is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for Enhancements and bug fixes
  • applyOperation and applyReducer now accept an optional index parameter. This param is used to create more elaborate error messages when invalid operations occur in your patches, #221.

  • Error messages are now nicely-formatted, they look like:

	The specified index MUST NOT be greater than the number of elements in the array
    name: OPERATION_VALUE_OUT_OF_BOUNDS
    index: 1
    operation: {
      "op": "add",
      "path": "/root/1",
      "value": "val"
    }
    tree: {
      "root": []
    }"
  • By default, prototype injection is not allowed and throws an error. If you want to pollute a prototype, you'll need to pass a flag banPrototypeModifications = false to all applyX functions. #219.
  • Bad behaviour when you replace an object with an array is now fixed. See #205.
Commits

The new version differs by 33 commits.

  • 476caa8 2.1.0
  • 56975ef Merge pull request #224 from Starcounter-Jack/fix-readme-ie8
  • 4dd2ece Make tests public in SauceLabs
  • 5b156f7 Merge branch 'master' into fix-readme-ie8
  • 4eab9ca Merge pull request #221 from ianvonholt/master
  • 0887799 Drop string interpolation use to support IE in tests
  • 0b4a1e1 Test error message formatting
  • d61f271 Add tested browsers matrix to README
  • 8db1342 Enable sauce connect in Travis config
  • be7f040 Add JS reporter and report to SauceLabs correctly
  • 934b603 Add FF, Safari and Chrome to tests
  • 8d87bea Text in browsers
  • 9ea1a18 Document the new index parameter in applyOperation and applyReducer
  • ee8e499 Format error messages nicely and test for op index logging
  • 1878ff4 Merge branch 'ianvonholt-fix' into master

There are 33 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Close version with latest changes

Hi!
I'm using this plugin in its latest version, and I'm having some problems when using updateOne and updateMany (if it doesn't find documents to update, it freezes).

I see that this is already fixed with this commit (b9d8abd) and I see that it is already in master.

Could you close version with what is currently in master to be able to use it? Since in the last released version these changes are not there.

TypeError: fn is not a function

In my code I had:

schema.plugin(patchHistory, {mongoose,...

Which threw the error:

TypeError: fn is not a function
    at Schema.plugin (/Users/himrc/Sites/dama/node_modules/mongoose/lib/schema.js:1133:3)

I was able to fix it by adding default. Not sure why I needed to do this.

The working code for me was:

schema.plugin(patchHistory.default, {mongoose,...

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected πŸ€–


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Bluebird promises module is a run-time dependency!

You have bluebird npm module as a dev dependency, but it's imported first thing and causes a failure at runtime if you haven't explicitly imported bluebird into your project.

At this point, bluebird isn't required to support promises, so I would remove the import and change the join function call to a Promises.all() instead.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.