auto-increment using loopback.js and MongoDB

前端 未结 3 2039
梦毁少年i
梦毁少年i 2021-01-14 17:07

i want to increase mongodb document number automatically using loopback.

I made function in mongo

 function getNextSequence(name) {
   var ret = db.         


        
相关标签:
3条回答
  • 2021-01-14 17:19

    You can do something like in this example for loopback 4

    let last_record = await this.testRepository.findOne({order: ['id DESC']});
    if(last_record) invoice.id = last_record.id+1;
    

    This will generate your model with the property:

    @property({
        type: 'number',
        id: true,
        default: 1,
        generated: false
      })
      id: number;
    

    Hopefully, this helps, please write me if there is any other code. Thanks

    0 讨论(0)
  • 2021-01-14 17:40

    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..
    
    0 讨论(0)
  • 2021-01-14 17:43

    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..
    
    0 讨论(0)
提交回复
热议问题