Thursday, 15 July 2010

javascript - Why can a MongoDb cursor be indexed as if it was an array? -



javascript - Why can a MongoDb cursor be indexed as if it was an array? -

i noticed if execute javascript script using mongo command, script can treat cursor object if array.

var conn = new mongo('localhost:27017'); var db = conn.getdb('learn'); db.test.remove({}); db.test.insert({foo: 'bar'}); var cur = db.test.find(); print(cur[0].foo); //prints: bar print(cur[1]); // prints: undefined

this seems should beyond capabilities of javascript language, since there no way "overload subscript operator". how work?

as documentation says, it special ability of driver. automagicly converts cursor[0] cursor.toarray()[0]. can prove overriding toarray() print function or new error().stack callstack back. here is:

at dbquery.a.toarray ((shell):1:32) @ dbquery.arrayaccess (src/mongo/shell/query.js:290:17) @ (shell):1:2

as can see, indexing calls arrayaccess. how? here have dbqueryindexaccess function, calls arrayaccess.

v8::handle<v8::value> arrayaccess = info.this()->getprototype()->toobject()->get( v8::string::new("arrayaccess")); ... v8::handle<v8::function> f = arrayaccess.as<v8::function>(); ... homecoming f->call(info.this(), 1, argv);

and here have code, sets indexed property handler function. wow, v8 api gives ability add together handler!

dbqueryft()->instancetemplate()->setindexedpropertyhandler(dbqueryindexaccess);

... , injects js cursor class, defined originaly in js.

injectv8function("dbquery", dbqueryft(), _global);

tl;dr: hacked in c++ source code of mongo shell.

javascript arrays mongodb

No comments:

Post a Comment