auto-increment using loopback.js and MongoDB

前端 未结 3 2038
梦毁少年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: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..
    

提交回复
热议问题