mongodb - 使用 loopback.js 和 MongoDB 自动递增

标签 mongodb increment auto-increment loopbackjs strongloop

我想使用环回自动增加 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"),

enter image description here

最佳答案

使用属性 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

将此值插入计数器

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

关于mongodb - 使用 loopback.js 和 MongoDB 自动递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33404504/

相关文章:

json - Haskell - 将 BSON 映射到 JSON 的正确方法 - 将代码放在哪里

javascript - 请解释这些++ 和 -- 操作

c - 在 c 中访问数组元素

javascript - Mongoose 自动增量

oracle - Oracle 中是否支持使用 Liquibase 的 Auto_Increment

mongodb - 从 Categories MySQL 表到 MongoDB 设计

javascript - Websocket 的正确方法

javascript - 当 "i"达到高于9时,失败

c# - 使用c#更新MySql上auto_increment ID列的值

python - MongoAlchemy 中的复杂字符串查询