Open andrealeo83 opened 3 years ago
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){
// ...
});
}
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.
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.
this works
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.