2014년 12월 27일 토요일

Unauthorized error when running mongo funcion from db.system.js (mongodb 2.4.8)

I am creating a sequence generator function getNextSequence() in Mongo 2.4.8 using the following within mongo shell:

Ø  function getNextSequence(name) {
   var ret = db.counters.findAndModify(
          {
            query: { _id: name },
            update: { $inc: { seq: 1 } },
            new: true,
            upsert: true
          }
   );

   return ret.seq;
}

Now when I try to run this function within mongo shell it worksfine.
Eg:

> getNextSequence("userid")
6
> 

But I want to save this function in the database and be able to use it from a Java program. So I ran the below to save it to db.system.js.save as shown below

db.system.js.save({    
_id: "getNextSequence",
value: function(name)
{   
var ret = db.counters.findAndModify({             query: { _id: name },             update: { $inc: { seq: 1 } },             new: true           }    );     return ret.seq;
                           }
})


Now when I try to run it from mongo shell using eval as shown below I get the following error
> db.eval("getNextSequence('userid')")
Mon Dec 22 09:49:10.183 { "ok" : 0, "errmsg" : "unauthorized" } at src/mongo/shell/db.js:571

So I created a new user with privilege role with access to anyAction and anyResource as shown below
> db.addUser({
...               user: "csdemouseranyaction",
...               pwd: "password",
...               privileges: [{
...                            resource: "anyResource",
...                            actions: [ "anyAction"]
...                            }],
...               roles: [ "dbowner","readWrite","readAnyDatabase" ]
...            })

But when I login as csdemouseranyaction and try eval I still get the same unauthorized error as shown below

> db.eval("getNextSequence('userid')")
Mon Dec 22 09:51:09.258 { "ok" : 0, "errmsg" : "unauthorized" } at src/mongo/shell/db.js:571

Note I am using Mongo 2.4.8.

Please advise how I can get to run the function from system.js without getting unauthorized error.




Are you running mongod with any special options?  (Like noscripting option?)

In the first case you were running this function on the client.  In the latter case you are attempting to run the function on the server (which, by the way, would lock up the server from other requests, which is why it's a bad idea performance-wise).

I would recommend against this approach for performance reasons.


댓글 없음:

댓글 쓰기