簡體   English   中英

Rethinkdb追加到數組(如果存在)

[英]Rethinkdb append to array if exists

在RethinkDB中,我的表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
}

謝謝!

你的邏輯很好。 這只是一些語法問題。

給定一個作者,如果不存在該作者,則將其插入,否則,使用您的邏輯附加視頻數組,這就是我的想法:

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的replace方法只有1個參數。 但是您也嘗試通過兩個參數: authorindex

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM