使用loopback.js和MongoDB自动递增 [英] auto-increment using loopback.js and MongoDB

查看:47
本文介绍了使用loopback.js和MongoDB自动递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用环回自动增加mongodb文档的数量.

i want to increase mongodb document number automatically using loopback.

我在mongo中实现了功能

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

它在mongo shell中工作.

It is working in mongo shell.

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

However when I insert using loopback.js browser (http://localhost:3000/explorer/), It is not working. 400 error(SytaxError) code is showing.

我不能在Loopback Rest API中使用mongo函数吗?

I can not use mongo function in loopback rest API ?

我认为问题是此行中的引号 getNextSequence("userid"),

I think problem is quotes in this line getNextSequence("userid"),

推荐答案

创建具有属性valuecollection

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

Now supposing your auto-increment collection name tweets.

将此值插入counters.

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

现在common/models/tweet.js

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

这篇关于使用loopback.js和MongoDB自动递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆