![](/img/trans.png)
[英]How to append to array only if it doesn't contain value with rethinkDB
[英]Rethinkdb append to array if exists
在RethinkDB中,我的表authors
具有以下布局:
{
id: 12,
videos: [1,2,3]
}
现在我有了这样的对象的新作者:
{
id: 12,
videos: [4,5]
}
如果作者现在已经存在,我想将新的视频4
和5
追加到视频列表中。 如果作者不存在,则按原样插入文档。 我的方法如下,但是没有用。
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
文档,而无需执行任何操作。 否则,我们将更新文档并将视频添加到其中。
要更新多个作者的数组,我们可以使用foreach
和expr
将数组转换为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个参数。 但是您也尝试通过两个参数: author
, index
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.