auto-increment using loopback.js and MongoDB

泄露秘密 提交于 2019-12-01 08:37:01

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..

I would love to add 1 more point to Robins Answer,you can add upsert:true so that it automatically creates the document if it doesn't exist

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,upsert: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..
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!