oliwer / mango

Pure-Perl non-blocking I/O MongoDB driver
https://metacpan.org/release/Mango
Artistic License 2.0
27 stars 12 forks source link

Any example how to use $mango->query ? #19

Closed pavelsr closed 8 years ago

pavelsr commented 8 years ago

Is it possible to execute db.loadServerScripts() via this method? And what about usage of Javascript functions?

Let me give you a particular example. I created a Javascript function at system.js collection which implements auto-incrementing.

Script for Mongo shell looks like:

db.dropDatabase();
db.counters.insert({_id: "userid", seq: 0 });
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;
    }
});
db.loadServerScripts();
db.users.insert({"login":"demo","user_id":getNextSequence("userid"),"password":"demo"});

(run it via mongo localhost:27017/mongopa init_db.js command)

But how to execute last two strings via Mango driver? Is it possible at all?

I tried to execute:

use Mango;
use Data::Dumper;
my $mango = Mango->new('mongodb://localhost:27017/mongopa');
my $reply  = $mango->query({}, {}, {}, {}, loadServerScripts(), {});
warn Dumper $reply;
my $oid = $mango->collection('users')->insert({'user_id' => 'getNextSequence("userid")', 'login' => 'demo2', 'password' => 'demo2' });
warn Dumper $oid;

but I got an error Undefined subroutine &main::loadServerScripts called ...

What am I doing wrong and could you please provide any example how to use $mango->query ?

oliwer commented 8 years ago

Hi. I'm afraid calling saved script is impossible for now. Even in the official MongoDB driver, we are asked to rewrite the scripts in perl. And loadServerScripts only works in the MongoDB shell.

Maybe @xdg could tell us more?

xdg commented 8 years ago

The mongo shell is written in JavaScript, so I think that database command just pulls down code and evals it it the shell. The Perl equivalent is to save Perl code (as text), in a collection, pull it down and then run it with eval(). Personally, I think that's not a robust, testable design, so I'd recommend just writing a Perl module with whatever reusable functions you want.

oliwer commented 8 years ago

Thanks for clearing that up.