auto-increment using loopback.js and MongoDB

2019-05-15 23:20发布

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

2条回答
聊天终结者
2楼-- · 2019-05-15 23:28

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..
查看更多
狗以群分
3楼-- · 2019-05-15 23:32

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..
查看更多
登录 后发表回答