incubator-couchdb-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Nils Breunese <N.Breun...@vpro.nl>
Subject Re: Dealing with sealed docs
Date Thu, 21 Apr 2011 12:08:31 GMT
Patrick Barnes wrote:

> My apologies - I have mis-remembered. No, there is no clone operator,
> but some functions will return a copy rather than a reference.
>
> I had a view that looked like:
> function(doc) {
>         if (doc.status=='active' && doc.doc_type=='group') {
>                 doc.path.pop();
>                 emit(doc.path, doc.display_name);
>         }
> }
> And it (on pre-1.0.2 couchdb) failed to generate the views properly,
> because doc.path.pop() was modifying the doc and the next views were
> receiving that modified version.
>
> In my case, changing the view to this fixed it:
> function(doc) {
>         if (doc.status=='active' && doc.doc_type=='group') {
>                 path = doc.path.slice(0);
>                 path.pop();
>                 emit(path, doc.display_name);
>         }
> }
>
> So doc.path.slice(0) copies the whole doc.path array for me so that I
> can modify it before emitting. No such neat method exists for objects
> unfortunately, but how about:
>
> function(doc) {
>   if(doc.type === 'schedule') {
>     var events = doc.events;
>     if (events) {
>       events.forEach(function(event) {
>         var broadcasters = event.broadcasters;
>         if (broadcasters) {
>           broadcasters.forEach(function(broadcaster) {
>             if(broadcaster === 'VPRO') {
> -              event.channel = doc.channel;
> -              event.channelName = doc.channelName;
> -              emit(event.end, event);
> +              var _event = {channel:doc.channel,
> channelName:doc.channelName};
> +              for (var k in event) _event[k]=event[k];
> +              emit(event.end, _event);
>             }
>           });
>         }
>       });
>     }
>   }
> }
>
> The members of _event are only references, but that should be okay
> because you're not modifying those, only adding two extra attributes to
> the new object created. (Not having to _copy_ every element should also
> make this approach much faster than using a generic 'clone' method)
>
> Hope that works. :-)

Thanks, I'm using this approach now and it seems to work.

Nils.
------------------------------------------------------------------------
 VPRO   www.vpro.nl
------------------------------------------------------------------------

Mime
View raw message