RethinkDB - Updating nested array

后端 未结 6 2317
隐瞒了意图╮
隐瞒了意图╮ 2021-02-13 02:09

I have a survey table that looks like so:

{
  id: Id,
  date: Date,
  clients: [{
    client_id: Id,
    contacts: [{
      contact_id: Id,
      score: Number,
         


        
6条回答
  •  一整个雨季
    2021-02-13 02:20

    You might need to get the array, filter out the desired value in the array and then append it again to the array. Then you can pass the updated array to the update method.

    Example

    Let's say you have a document with two clients that both have a name and a score and you want to update the score in one of them:

    {
      "clients": [
        {
          "name":  "jacob" ,
          "score": 200
        } ,
        {
          "name":  "jorge" ,
          "score": 57
        }
      ] ,
      "id":  "70589f08-284c-495a-b089-005812ec589f"
    }
    

    You can get that specific document, run the update command with an annonymous function and then pass in the new, updated array into the clients property.

    r.table('jacob').get("70589f08-284c-495a-b089-005812ec589f")
      .update(function (row) {
        return {
          // Get all the clients, expect the one we want to update
          clients: row('clients').filter(function (client) {
            return client('name').ne('jorge')
          })
          // Append a new client, with the update information
          .append({ name: 'jorge', score: 57 })
        };
      });
    

    I do think this is a bit cumbersome and there's probably a nicer, more elegant way of doing this, but this should solve your problem.

    Database Schema

    Maybe it's worth it to create a contacts table for all your contacts and then do a some sort of join on you data. Then your contacts property in your clients array would look something like:

    {
      id: Id,
      date: Date,
      clients: [{
        client_id: Id,
        contact_scores: {
          Id: score(Number)
        },
        contact_feedbacks: {
          Id: feedback(String)
        }
      }]
    }
    

提交回复
热议问题