I am using loopback4 with MongoDB.
I have a counter property in my model, and would like to do atomic operation to increment/decrement that counter.
My implementation now is using ExtendedOperators $inc to add or sub calculations. But I found that despite of my jsonSchema set to minimum:0, the counter will be negative value when $inc:{counter:-1} at counter value 0.
I think I can use Mongo Document Validation to set value range constraint, But I cant find the right way in repository code to do this.
Should I set it manually through Mongo Shell? But how can I do error handling?
model
@property({
type: 'number',
jsonSchema:{
minimum:0,
}
})
count: number;
controller
async incrementCountById(
@param.path.string('id') id: string
): Promise<void> {
await this.userRepository.updateById(id, {$inc: {count: -1} });
}
repository
const config = {
allowExtendedOperators: true,
};
Any advice would be appreciated:)