javascript - RethinkDB - 更新嵌套数组

标签 javascript database node.js rethinkdb

我有一个如下所示的调查表:

{
  id: Id,
  date: Date,
  clients: [{
    client_id: Id,
    contacts: [{
      contact_id: Id,
      score: Number,
      feedback: String,
      email: String
    }]
  }]
}

我需要更新特定联系人下的 scorefeedback 字段。目前,我正在运行这样的更新:

function saveScore(obj){
  var dfd = q.defer();
  var survey = surveys.get(obj.survey_id);

  survey 
    .pluck({ clients: 'contacts' })
    .run()
    .then(results => {

      results.clients.forEach((item, outerIndex) => {
        item.contacts.forEach((item, index, array) => {
          if(Number(item.contact_id) === Number(obj.contact_id)) {
            array[index].score = obj.score;
            console.log(outerIndex, index);
          }
        });
      });

      return survey.update(results).run()
    })
    .then(results => dfd.resolve(results))
    .catch(err => dfd.resolve(err));

  return dfd.promise;
};

当我查看 update方法,它指定如何更新嵌套的键:值对。但是,我找不到任何示例来更新数组中的单个项目。

有没有更好更简洁的方法来更新嵌套数组中的项目?

最佳答案

您可能需要获取数组,过滤 出数组中所需的值,然后将其再次附加到数组中。然后您可以将更新后的数组传递给 update 方法。

示例

假设您有一个包含两个客户端的文档,这两个客户端都有一个 name 和一个 score,并且您想更新其中一个的分数:

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

您可以获取该特定文档,使用匿名函数运行 update 命令,然后将更新后的新数组传入 clients 属性。

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 })
    };
  });

我确实认为这有点麻烦,并且可能有更好、更优雅的方式来执行此操作,但这应该可以解决您的问题。

数据库架构

也许值得为您的所有联系人创建一个 contacts 表,然后对您的数据进行某种形式的连接。然后您的 clients 数组中的 contacts 属性将类似于:

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

关于javascript - RethinkDB - 更新嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30265313/

相关文章:

database - Play Framework 2.1密码加密

node.js - 有没有办法编译 node.js 源文件?

node.js - 启动 Electron App 后自动运行 Node.js 服务器文件

javascript - 如何在最后一个值之后循环这个函数

javascript - 拖动时元素的jQuery UI舍入宽度

sql - 如何在 postgresql 中创建 *swap 表(带/索引)

Python DB API 列表表

node.js - 声明自定义异常以与 Firestore 可调用函数和 VueJS 一起使用

javascript - 检查组合字符串+数组的所有匹配项

javascript - RequireJS 未加载 Firebase,未定义