Why can a MongoDb pointer be indexed as if it were an array?

I noticed that if I execute a JavaScript script using a command mongo, the script can process the cursor object as if it were an 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

It seems that this should be beyond the capabilities of the JavaScript language, since it is impossible to "overload the index operator". So how does it work?

+4
source share
1 answer

, . cursor[0] cursor.toArray()[0]. , toArray() new Error().stack, . :

at DBQuery.a.toArray ((shell):1:32)
at DBQuery.arrayAccess (src/mongo/shell/query.js:290:17)
at (shell):1:2

, arrayAccess. ? dbQueryIndexAccess, arrayAccess.

v8::Handle<v8::Value> arrayAccess = info.This()->GetPrototype()->ToObject()->Get(
                v8::String::New("arrayAccess"));
...
v8::Handle<v8::Function> f = arrayAccess.As<v8::Function>();
...
return f->Call(info.This(), 1, argv);

, . WOW, API v8 !

DBQueryFT()->InstanceTemplate()->SetIndexedPropertyHandler(dbQueryIndexAccess);

... JS, JS.

injectV8Function("DBQuery", DBQueryFT(), _global);

Tl; dr: ++ mongo.

+4

Source: https://habr.com/ru/post/1545278/


All Articles