mongoose-sequence icon indicating copy to clipboard operation
mongoose-sequence copied to clipboard

Enable the library conditionally

Open andrealeo83 opened this issue 3 years ago • 4 comments

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.

andrealeo83 avatar Jun 04 '21 11:06 andrealeo83

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){
     // ...
  });
}

ramiel avatar Jun 05 '21 20:06 ramiel

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.

andrealeo83 avatar Jun 07 '21 07:06 andrealeo83

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.

ramiel avatar Jun 07 '21 09:06 ramiel

this works

andrealeo83 avatar Jun 07 '21 13:06 andrealeo83