mongoose-history-plugin icon indicating copy to clipboard operation
mongoose-history-plugin copied to clipboard

Can't use one shared collection for multiple schemas

Open StefanM98 opened this issue 5 years ago • 2 comments

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!

StefanM98 avatar Dec 21 '19 20:12 StefanM98

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

Masquerade-Circus avatar May 17 '20 13:05 Masquerade-Circus

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

kushalarora92 avatar Feb 23 '21 13:02 kushalarora92