Search code examples
c++v8

V8 - SetAccesor can't add to a existing template


I have the following code :

        while (bson_iter_next(&iter))
        {
            const char* key = bson_iter_key(&iter);
            if (!_paths.count(key)) 
            {
                _template->SetAccessor(
                    String::NewFromUtf8(isolate, key),
                    &BSONObject::getter,
                    &BSONObject::setter
                );
            }
        }

    Local<Object> obj = _template->NewInstance();

I build a object with all fields in a document BSON. I have a list of documents and they all go through this code. I realized that if the first have not fields which others have they won't be define. I explain :

BSON 1 : {foo: 3}
BSON 2 : {foo: 2, boo: 4}

When I will use my getter in JS he will show me :

BSON 1 : {foo: 3}
BSON 2 : {foo: 2}

How I can add this field's accessor ?


Solution

  • Don't use the same ObjectTemplate for objects with different numbers of properties.

    I can think of two alternatives; which one is better depends on the rest of your app:

    • create a fresh Object every time, and call SetAccessor (or CreateDataProperty?) directly on that Object. No ObjectTemplate required.

    • use SetHandler on the ObjectTemplate to install a single handler that intercepts all property queries.