Rethinkdb追加到数组如果存在

Rethinkdb append to array if exists

本文关键字:如果 存在 数组 追加 Rethinkdb      更新时间:2023-09-26

在RethinkDB中,我有一个表authors,具有以下布局:

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

现在我用这样的对象得到新的作者:

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

如果作者现在已经存在,我想将新的视频45添加到视频列表中。如果author不存在,就按原样插入文档。我的方法是这样的,但它不起作用。

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
}

谢谢!

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

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

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对象

那样使用[]
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"))}
          })
        )
    }
  )
})

应该这样做:

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

lambda for replace方法只有一个参数。但是你试图传递2个参数:author, index .