Automatically increase property value in Strongloop loopback model

Is there a built-in way to automatically increase the value of a model property, is this Strongloop loopback? This model has a property called orderNumber, and I want it to start at 1 and increment by 1 each time a new model is created. This model is stored in the Mongo database. If loopback Strongloop doesn't have a built-in way, then what would be considered best practice using javaScript, Node and mongoDB?

Thanks,

+7
javascript rest mongodb loopbackjs strongloop
source share
3 answers

Ok, this solution works, but I bypass Loopback and the "mongoDB connector". That's what I'm doing.

For a model called Sequence that looks like this:

{ "_id": { "$oid": "54ab3ec0cc074e24144f26d7" }, "collection": "SpecialOrder", "value": 113 } 

I'm doing it:

 mongoConnector = app.dataSources.MyMongoDBConnectorName.connector; mongoConnector.collection("Sequence").findAndModify({collection: 'SpecialOrder'}, [['_id','asc']], {$inc: { value: 1 }}, {new: true}, function(err, sequence) { if(err) { console.log(err.message); } else { // Do what I need to do with new incremented value sequence.value } }); 

There seems to be a built-in way for LoopbackJS to do this. A lot to go through to increase the value.

Thanks,

Warren bell

+3
source share

Have the same problem, but with Postgres. Fixed using only one id column identifier manually in the database (set the type to SERIAL, which means automatic growth in Postgres). I think the problem can be solved this way in any database.

+1
source share

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!

+1
source share

All Articles