Masquerade-Circus / mongoose-history-plugin

Mongoose plugin that saves history in JsonPatch format and SemVer format.
Apache License 2.0
47 stars 25 forks source link

Can't use one shared collection for multiple schemas #14

Open StefanM98 opened 4 years ago

StefanM98 commented 4 years ago

Problem: It is stated that we can use multiple history collections or one shared collection for the history schemas. However, it is not possible to use a shared collection to hold the history of more than one schema. A mongoose OverwriteModelError is thrown when using the plugin on multiple schemas with the same modelName.

Possible Solution: After looking at the code, it seems that no check is performed to see if the model already exists before creating it. As a temporary fix, I changed the code to this:

...
let mongoose = pluginOptions.mongoose;
const collectionIdType = options.collectionIdType || mongoose.Schema.Types.ObjectId;
let Model;
  try {  // Check if the model exists
    Model = mongoose.model(pluginOptions.modelName);
  } catch (e) {}

  if (!Model) {
     ... // schema code
     Model = mongoose.model(pluginOptions.modelName, Schema);
  }
...

That seemed to fix the issue. Can you please make a new release with a similar fix? Thanks for the great plugin!

Masquerade-Circus commented 4 years ago

Hi @StefanM98 Can you put a full example to see the model/schemas declarations?

kushalarora92 commented 3 years ago

Thanks, @StefanM98. You're are a savior.