rethinkdb / docs

RethinkDB documentation
http://rethinkdb.com/docs
Apache License 2.0
117 stars 167 forks source link

Insert - conflict options with a function on nested data #1202

Open jarekkowol opened 7 years ago

jarekkowol commented 7 years ago
r.table('table').insert({
    id: id,
    session: session,
    sockets: [{
        id: socket_id
    }]
}, {conflict: function(id, oldDoc, newDoc) {
    return newDoc.merge({
        session: session,
        sockets: sockets(oldDoc('sockets'), newDoc('sockets'))
    });
}})

Adding new objects works fine:

function sockets(oldDoc, newDoc) {
    return oldDoc.append({
        id: socket_id
   });
}

Is it possible to update / remove nested data using oldDoc object?

thinklinux commented 7 years ago

@jarekkowol did you resolved your issue?

Conflict handling is made for updating or keeping the old version of a document. I'm not sure that your example with .append is actually working as expected. You probably wanted to do return oldDoc('sockets').append({id: socket_id}).

As for updating nested objects - it's possible. It is the example that you have with merge and then if you have an array you can use map, forEach and filter to construct the new array that you want to merge. Example:

return newDoc.merge({
  session: session,
  sockets: r.merge(newDoc('sockets'), oldDoc('sockets')).map((socket) => {
    // You do your stuff here
  })
});