使用loopback.js和MongoDB自动增量

2024-01-05

我想使用环回自动增加 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/ http://localhost:3000/explorer/),它不起作用。 显示 400 错误(SytaxError)代码。

我无法在环回 REST API 中使用 mongo 函数?

我认为问题是这一行的引号getNextSequence("用户 ID"),


创建一个集合counters有属性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": []
}

现在假设你的自增集合名称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..
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用loopback.js和MongoDB自动增量 的相关文章

随机推荐