Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable the library conditionally #110

Open
andrealeo83 opened this issue Jun 4, 2021 · 4 comments
Open

Enable the library conditionally #110

andrealeo83 opened this issue Jun 4, 2021 · 4 comments

Comments

@andrealeo83
Copy link

Is it possible to apply the sequence only if a condition is applied?

For example:

User Model fields:
UUID
user_id -> inc_field
type: "Student" or "Teacher"

I want to generate the sequence for the user_id field using mongoose-sequence only if type == "Student" and not for type== "Teacher""

For me it's important to disable the sequence generation for certain conditions to preserve the performance.

@ramiel
Copy link
Owner

ramiel commented Jun 5, 2021

In this case I think the best option is to disable automatic increment and manually increment the counter when needed. Look at the documentation: https://github.com/ramiel/mongoose-sequence#not-automatic-sequences

A simple way is to disable the library hook and write your own post/pre save hook. In the hook you can determine the type of user and if the type is student you can call user.setNext. An example code

UserSchema.plugin(AutoIncrement, {id:'student_counter', inc_field: 'user_id', disable_hooks: true});

// then, somewhere in your code, probably in a mongoose hook
if(user.type === 'student') {
  user.setNext('student_counter', function(err, user){
     // ...
  });
}

@andrealeo83
Copy link
Author

I see from code setNext exec mongoose save method. I don't want to save again the document to avoid further saving on the db and improve performance. I think it's preferable to conditionally activate the sequence and save only one time the document to MongoDB in my code.

@ramiel
Copy link
Owner

ramiel commented Jun 7, 2021

Ok, I see your use case. So you'd want something like this:

UserSchema.plugin(AutoIncrement, {
  id:'student_counter', 
  inc_field: 'user_id', 
  condition: (user) => user.type === 'student'
});

I'm not sure this is generally useful but you can provide a PR if you want.

@andrealeo83
Copy link
Author

this works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants