Как удалить / обновить массив вложенных документов - PullRequest
1 голос
/ 15 июня 2019

Учитывая документ, как показано ниже, как я могу удалить или обновить вложенный документ ingredients?Любая помощь, я новичок в этом rethinkdb.В таблице хранятся эти документы, называемые рецептами.

[
    {
        "cook": "9 min",
        "id": "be63fc32-c1b5-4c67-a967-b6868f095216",
        "inactive": "20 min",
        "ingredients": [
            "2 cups fresh parsley leaves, chopped",
            "8 large sprigs fresh thyme, chopped",
            "4 large sprigs fresh rosemary, chopped",
            "3 cloves garlic, minced",
            "1 small shallot, diced",
            "2 tablespoons cracked black peppercorns",
            "2 tablespoons cracked pink peppercorns",
            "1 1/4 cups extra-virgin olive oil",
            "8 skin-on chicken thighs",
            "Flaky salt, such as Maldon, for seasoning",
            "Salad, for serving"
        ],
        "level": "Easy",
        "prep": "5 min",
        "title": "Asian Grilled Salmon",
        "total": "34 min",
        "yields": "6 servings"
    },
    ....

Я пробовал, как вы видите ниже, и это сработало.Но я хочу знать, есть ли лучший способ.

class Ingredients:
    def __init__(self, name):
        self.name = name

    @classmethod
    def update(self, recipe, name, position):
        __db__ = recipe.__class__.__db__()
        __table__ = recipe.__class__.__table__()
        result = (
            __table__.get(recipe.id)
            .update(
                {
                    "ingredients": __db__.r.row["ingredients"].change_at(
                        position, name
                    )
                }
            )
            .run(__db__.conn)
        )

        return recipe.ingredients

    @classmethod
    def destroy(self, recipe, recipe_name):
        __db__ = recipe.__class__.__db__()
        __table__ = recipe.__class__.__table__()
        __table__.get(recipe.id).update(
            {
                "ingredients": __db__.r.row["ingredients"].filter(
                    lambda name: name != recipe_name
                )
            }
        ).run(__db__.conn)

        return recipe.ingredients

Ingredients class - это попытка смоделировать часть ingredients: [..] родительского документа в Python.

1 Ответ

2 голосов
/ 17 июня 2019

Для обновления вы можете перебирать ингредиенты с помощью map, найти тот, который хотите обновить, и изменить его значение:

r.db("test").table("sample").get("be63fc32-c1b5-4c67-a967-b6868f095216")
   .update({
     ingredients: r.row("ingredients").map(function(sub){  
       return r.branch(sub.eq("2 cups fresh parsley leaves, chopped"),
         "2 cups fresh baby poo, marinated", sub)
     })
   })  

Для удаления вы можете использовать функцию difference:

r.db('test').table('sample').get('be63fc32-c1b5-4c67-a967-b6868f095216')
  .update({ingredients: r.row('ingredients')
    .difference(["4 large sprigs fresh rosemary, chopped"])});  
...