Search code examples
mongodbincrementauto-incrementloopbackjsstrongloop

auto-increment using loopback.js and MongoDB


i want to increase mongodb document number automatically using loopback.

I made function in mongo

 function getNextSequence(name) {
   var ret = db.counters.findAndModify(
          {
            query: { _id: name },
            update: { $inc: { seq: 1 } },
            new: true
          }
   );

   return ret.seq;
}


db.tweet.insert(
{
   "_id" : getNextSequence("userid"),
  "content": "test",
  "date": "1",
  "ownerUsername": "1",
  "ownerId": "1"
}
)

It is working in mongo shell.

However when I insert using loopback.js browser (http://localhost:3000/explorer/), It is not working. 400 error(SytaxError) code is showing.

I can not use mongo function in loopback rest API ?

I think problem is quotes in this line getNextSequence("userid"),

enter image description here


Solution

  • Create a collection counters with properties value and collection

    {
      "name": "counters",
      "base": "PersistedModel",
      "idInjection": true,
      "options": {
        "validateUpsert": true
      },
      "properties": {
          "type": "number",
          "collection": "string"
    
      },
      "validations": [],
      "relations": {},
      "acls": [
        {
          "accessType": "*",
          "principalType": "ROLE",
          "principalId": "$everyone",
          "permission": "ALLOW"
        }
      ],
      "methods": []
    }
    

    Now supposing your auto-increment collection name tweets.

    Insert this value to counters.

    {
      "value" : 0, 
      "collection" : "tweet"
    }
    

    Now common/models/tweet.js

    tweet.observe('before save', function (ctx, next) {
    
            var app = ctx.Model.app;
    
            //Apply this hooks for save operation only..
            if(ctx.isNewInstance){
                //suppose my datasource name is mongodb
                var mongoDb = app.dataSources.mongodb;
                var mongoConnector = app.dataSources.mongodb.connector;
                mongoConnector.collection("counters").findAndModify({collection: 'tweet'}, [['_id','asc']], {$inc: { value: 1 }}, {new: true}, function(err, sequence) {
                    if(err) {
                        throw err;
                    } else {
                        // Do what I need to do with new incremented value sequence.value
                        //Save the tweet id with autoincrement..
                        ctx.instance.id = sequence.value.value;
    
                        next();
    
                    } //else
                });
            } //ctx.isNewInstance
            else{
                next(); 
            }
        }); //Observe before save..