Search code examples
rethinkdbrethinkdb-javascript

Update column with array entry; create column if it does not exist


                            r.table("bets").filter({id: betID}).update({
                                votes: r.row('votes').append({
                                    userID: userID,
                                    vote: vote
                                })
                            }).run(connection, function(err, result) {
                                // ...
                            });

My goal ist to update a document in the bets table with the given betID. I want to update the column votes, which might not exist. If it does not exist, I want to create the column, and append the array element afterwards. If it exists, I just want to append the array element. result.replaced returns 1, which is correct, but the column votes is not created... any idea?


Solution

  • Found the solution:

                                var newVote = {
                                    userID: userID,
                                    vote: vote
                                };
    
                                r.table("bets").filter({id: betID}).update({
                                    votes: r.row('votes').default([]).append(newVote)
                                }).run(connection, function(err, result) {
    
                                });
    

    See. https://rethinkdb.com/api/javascript/update/