I want to share my approach, similar to the answer of the author, but using Loopback methods. Here is the Sequence model I 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": [] }
In this model, you can save as many sequences as you want. Then I create the sequence I need with this script (in this case, the 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, every time I need an order number to create an order, first I update the order entry in the model's Sequence , increasing 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, ... }); });
Hooray!
Bakh domalak
source share