【问题标题】:auto-increment using loopback.js and MongoDB使用 loopback.js 和 MongoDB 自动递增
【发布时间】:2016-01-29 00:29:38
【问题描述】:

我想使用环回自动增加 mongodb 文档数。

我在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"
}
)

它在 mongo shell 中工作。

但是,当我使用 loopback.js 浏览器 (http://localhost:3000/explorer/) 插入时,它无法正常工作。 显示 400 错误(SytaxError)代码。

我不能在 loopback rest API 中使用 mongo 函数?

我认为问题在于这一行中的引号 getNextSequence("userid"),

【问题讨论】:

  • 您是否尝试过“保存前”的解决方案?

标签: mongodb increment auto-increment loopbackjs strongloop


【解决方案1】:

使用属性valuecollection 创建集合counters

{
  "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": []
}

现在假设您的自动增量集合名称 tweets

将此值插入counters

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

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

【讨论】:

    【解决方案2】:

    我很想为 Robins Answer 再加 1 分,您可以添加 upsert:true 以便在文档不存在时自动创建文档

    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】:

      您可以在此示例中为环回 4 执行类似操作

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

      这将生成带有属性的模型:

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

      希望这有帮助,如果有任何其他代码,请写信给我。谢谢

      【讨论】:

        【解决方案4】:

        如果您想在环回方法中直接使用 MongoDB 运算符,您需要启用“allowExtendedOperators”选项,您可以在每个模型或数据源级别执行此操作(将适用于使用数据源的所有模型) .

        数据源.json:

          "MongoDs": {
            "host": "127.0.0.1",
            "port": 27017,
            "url": "mongodb://localUser:MYPASSWORD!@127.0.0.1:27017/test-database",
            "database": "test-database",
            "password": "MYPASSWORD!",
            "name": "MongoDs",
            "user": "localUser",
            "useNewUrlParser": true,
            "connector": "mongodb",
            "allowExtendedOperators": true
          },

        【讨论】:

          猜你喜欢
          • 2015-11-10
          • 2013-07-21
          • 2015-02-18
          • 2017-04-20
          • 2016-03-07
          • 2020-01-11
          • 2018-12-06
          • 2017-01-11
          • 2013-08-24
          相关资源
          最近更新 更多