given sample data like:
{
'id': 1,
'things': [{'name': 'a'},{'name': 'b'},{'name': 'c'}]
}
how do I update the document removing the array item with name of 'b' from the embedded array?
r.table('test')
.get(1)
.update({things: r.row('things')????});
You can remove elements from the end of an array using pop, from the beginning using shift, or from the middle using splice. The JavaScript Array filter method to create a new array with desired items, a more advanced way to remove unwanted elements.
If you want a new array with the deleted positions removed, you can always delete the specific element and filter out the array. It might need an extension of the array objectfor browsers that don't implement the filter method, but in the long term it's easier since all you do is this:
If you know the value you want to remove from an array you can use the splice method. First you must identify the index of the target item. You then use the index as the start element and remove just one element. This is a simple example where the elements are integers.
If you want to remove multiple items that match your criteria there is a glitch. As the items are removed from the array the index still increments and the next item after your matched value is skipped. The simple solution is to modify the above example to decrement the index variable so it does not skip the next item in the array.
You can use the update
command along with filter
to filter the elements in an array and pass to along to update
.
r.table('30848200').get(1).update(function (row) {
return {
'things': row('things')
.filter(function (item) { return item('name').ne('b') })
}
})
Basically, you'll be overwriting things
with the filtered array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With