I want to share my approach, which is similar to the author's answer, but with using Loopback's methods.
Here is the Sequence
model I've created:
{
"name": "sequence",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string",
"required": true
},
"value": {
"type": "number",
"required": true
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": []
}
You can store as many sequences as you want in this model. Then I create a sequence I need with this script (in this case order
sequence):
var app = require('./server/server');
var Sequence = app.models.Sequence;
Sequence.findOrCreate({
where: {
name: 'order'
}
}, {
name: 'order',
value: 0
}, function (err) {
if (err) {
console.log(err);
}
process.exit();
});
Now everytime I need order number to create an order, first I update the order
record in Sequence
model by incrementing its value
and then use it:
var Sequence = Order.app.models.Sequence;
Sequence.findOne({
where: {
name: 'order'
}
})
.then(function (orderNumber) {
orderNumber.value++;
return orderNumber.save();
})
.then(function (orderNumber) {
Order.upsert({
orderNumber: orderNumber.value,
...
});
});
Cheers!