Reputation: 33
I have documents similar to this
{id: 0, a: [0, 1], b: null, c: 4, d: 6, e: 7}
{id: 0, a: [1,2], b: 3, c: 5, d: null, f:8}
I am wanting to batch insert documents so that a
is added to the array as a set, null values are overwritten but other values stay as is. So the resulting document in the table would be
{id:0, a:[0,1,2], b:3, c:4, d:6, e:7, f:8}
I tried doing the following in the data explorer but am getting the error SyntaxError: Unexpected token return
r.table('foo').insert(
[{id: 0, a: [0, 1], b: null, c: 4, d: 6}, {id: 0, a: [1,2], b: 3, c: 5, d: null}],
{
conflict: function(id, old_doc, new_doc){
return (new_doc.keys().map(function (key) {
return r.branch(key.eq('a'),
[key, old_doc('a').setUnion(new_doc('a'))],
r.branch(old_doc(key).eq(null),
[key, new_doc(key)],
[key, old_doc(key)])
)
})).coerceTo('object')
}
})
I also thought about using merge for this case but would need to be able to define a conflict strategy for identical keys and it doesn't seem like you can do that at this point issue #873.
EDIT: The function I ended up using after @mlucy answer and some other changes.
r.table('foo').insert(
[{id: 0, a: [0, 1], b: null, c: 4, d: 6, e: 7}, {id: 0, a: [1,2], b: 3, c: 5, d: null, f:8}],
{
conflict: function(id, old_doc, new_doc){
return (new_doc.keys().setUnion(old_doc.keys()).map(function (key) {
return r.branch(old_doc.hasFields(key).and(new_doc.hasFields(key).not()),
[key, old_doc(key)],
new_doc.hasFields(key).and(old_doc.hasFields(key).not()),
[key, new_doc(key)],
r.branch(key.eq('a'),
[key, old_doc('a').setUnion(new_doc('a'))],
r.branch(old_doc(key).eq(null).and(new_doc(key).eq(null).not()),
[key, new_doc(key)],
[key, old_doc(key)])
)
)
})).coerceTo('object')
}
})
Upvotes: 0
Views: 152
Reputation: 5289
The return in return r.branch(old_doc(key).eq(null),
shouldn't be there, which is why you're getting that error. You also need key.eq(a)
to be key.eq('a')
, and set_union
should be setUnion
. Finally, I think you should be calling FOO.coerceTo('object')
rather than r.object(FOO)
there.
Upvotes: 1