Rethinkdb 附加到数组(如果存在)

Rethinkdb append to array if exists

在 RethinkDB 中,我有一个具有以下布局的 table authors

{
  id: 12,
  videos: [1,2,3]
}

现在我有了像这样的对象的新作者:

{
  id: 12,
  videos: [4,5]
}

如果作者现在已经存在,我想将新视频 45 添加到视频列表中。 如果作者不存在,只需按原样插入文档。 我的方法如下,但是没有用。

r.table('authors').getAll(4, 3, 2, 1, {index: 'id'})
    .replace(function(author, index) {
        return r.branch(
            author.eq(null),
            {
                id: index,
                videos: [1,2,3]
            },
            author
        );
    })

-> 响应:

{
    "deleted": 0 ,
    "errors": 3 ,
    "first_error":  "Expected 2 arguments but found 1." ,
    "inserted": 0 ,
    "replaced": 0 ,
    "skipped": 0 ,
    "unchanged": 0
}

谢谢!

lambda for replace 方法只有 1 个参数。但是您也尝试传递 2 个参数:authorindex.

应该这样做:

r([4, 3, 2, 1]).foreach(function(id) {
  return r.table('authors').get(id).replace(function(row) {
    return r.branch(row.eq(null), {id: id, videos: [1, 2, 3]}, row);
  });
});

你的逻辑很好。这只是一些语法问题。

给定作者,如果作者不存在,则插入它,否则,追加视频数组,这是我的想法,使用您的逻辑:

var author = {
    id: 12,
  videos: [9, 10]
};

r.table('authors').insert(author).do(
    function (doc) {
        return r.branch(doc('inserted').ne(0),
          r.expr({inserted: 1}),
          r.table('authors').get(author["id"]).update(function(doc) {
            return {videos: doc('videos').union(author["videos"])}
          })
        )
    }
)

如果插入成功,说明我们没有相同的文档id,我们什么都不用做。否则,我们将更新文档并将视频附加到其中。

要更新多个作者的数组,我们可以使用 foreachexpr 将数组转换为 ReQL 对象。但是,在这种情况下,我们使用 bracket 来获取字段,而不是像 JavaScript object

中那样使用 []
var authors = [{
    id: 12,
    videos: [90, 91]
},{
    id: 14,
    videos: [1, 2]
}];

r.expr(authors).forEach(function(author) {

  return r.table('authors').insert(author).do(
    function (doc) {
        return r.branch(doc('inserted').ne(0),
          r.expr({inserted: 1}),
          r.table('authors').get(author("id")).update(function(doc) {
            return {videos: doc('videos').union(author("videos"))}
          })
        )
    }
  )

})