question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Avoid global plugins in model

See original GitHub issue

Do you want to request a feature or report a bug? Feature What is the current behavior? Hi, I’ve a module who uses mongoose as mutex (with it’s own schema and model), to validate the mutex is taken I just insert the document with a unique index, so if I get an E11000 error I know the mutex is taken.

In other hand I’ve a plugin who checks if a document with unique index can be saved, so instead of throwing a E11000 error it throws a validation error. My module must be agnostic to the plugins.

Is there a way to tell a schema/model not to apply a global plugin? If the current behavior is a bug, please provide the steps to reproduce.

"use strict";
const mongoose = require("mongoose");

//comment 2 lines above to make it work
const beautifyUnique = require("mongoose-beautiful-unique-validation");
mongoose.plugin(beautifyUnique);
//a simplified mutex
const mutex = new mongoose.Schema({
  name: {
    type: String,
    unique: true,
    required: true,
  },
});
mutex.static({
  async getMutex(name) {
    try {
      const localMutex = await this.create({name});
      return localMutex;
    } catch (err) {
      if (err.code === 11000) {
        const localError = new Error("mutex can't be acquired");
        localError.name = "mutexError";
        throw localError;
      }
      throw err;
    }
  },
});
mutex.method({
  async release() {
    return await this.remove();
  },
});
const Mutex = mongoose.model("Mutex", mutex);
async function doSomething() {
  try {
    const localMutex = await Mutex.getMutex("test");
    //inner logic...
    //wait for a while
    setTimeout(() => localMutex.release(), 100);
    return true;
  } catch (err) {
    if (err.name === "mutexError") {
      return false;
    }
    //this could be any other logic error
    else throw err;
  }
}
async function main() {
  await mongoose.connect("mongodb://localhost/test", {
    useUnifiedTopology: true,
    useNewUrlParser: true,
    useCreateIndex: true,
  });
  await Mutex.deleteMany(); //just for his test
  //doSomething twice
  for (let i = 0; i < 2; i++) {
    doSomething().then((res) => {
      if (res) console.log(i, "DONE");
      else console.warn(i, "NOT DONE");
    }, console.error);
  }
  await new Promise((res) => setTimeout(res, 200));
  doSomething().then((res) => {
    if (res) console.log("LAST DONE");
    else console.warn("LAST NOT DONE");
  }, console.error);
}
main();

In my code the plugin and the model doesn’t know about each other and never will, this is only one example, I’ve several problems like this.

What is the expected behavior?

That I could use a external module who creates a model and this model don’t get global plugins applied. maybe in the schema options like {plugins: false} or something like that.

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that “latest” is not a version.

mongoose: 5.11.10 mongo: 4.2 node: 14.15.4

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:8

github_iconTop GitHub Comments

1reaction
vkarpov15commented, Jan 8, 2021

You can also tell the plugin to explicitly avoid a certain schema:

const plugin = require('myplugin');

mongoose.plugin((schema, options) => {
  if (schema === schemaToExclude) {
    return;
  }
  return plugin(schema, options);
});
0reactions
chumagercommented, Dec 2, 2021

Hi @vkarpov15, I already solved for mi FW, my problem is if someone uses my modules, I added caveats in the readme.

instead of mongoose.plugin(plugin, options) I added a wrapper.

//for each global plugin
mongoose.plugin((schema, options)=>{
  if (!schema.get("noGlobalPlugin")) schema.plugin(plugin, options);
}, options);
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to avoid global variables in JavaScript? - Stack Overflow
The easiest way is to wrap your code in a closure and manually expose only those variables you need globally to the global...
Read more >
Manage plug-ins in a single solution - Power Apps
The correct solution is to avoid the situation where the same plug-in assembly is included in multiple solutions. In both examples above, when ......
Read more >
Documentation - Global: Plugin - TypeScript
A global plugin is global code that changes the shape of some global. As with global-modifying modules, these raise the possibility of runtime...
Read more >
Using Gradle Plugins
Where «plugin id» and «plugin version» must be constant, literal, strings and the apply statement with a boolean can be used to disable...
Read more >
Create a Custom Vue.js Plugin in < 1 Hour [Code Included]
Add one or more global assets (directives, filters, transitions, etc.) Add component options by global mixins. Add Vue instance methods by ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found