I was just playing around the concepts of sailsjs then I came to know we cannot use auto increments in sails if we are using mongodb as our database. I cannot able to use the auto increments even for the non primary key attributes. Is there any special methods to use auto increments operations for an attribute which is not a primary key? Thanks in advance
If waterline doesn't support it automatically, which is what it seems like, you can do it in the beforeCreate
lifecycle callback of waterline. It is independent of any database adapter.
I would recommend you to take a look at how lifecycle callbacks work for clear understanding. Workflow would be something like following. Before creating any record you would check the count of records of the Model
. Then update the x
field of the records to be created as one more than that found count and pass the batton.
beforeCreate: function(obj, next){
Model.count().exec(function(err, cnt){
if(err) next(err);
else{
obj['x'] = cnt + 1;
next(null);
}
})
}
Counting the records is not the perfect way. You can change the way you like to find the value of auto-incremented value. Purpose of this example is to give you intuition of how it can be done. This is not the exact alternative of autoincrement but it's an effective workaround I guess. Hope it helps you.