[英]How to append to array only if it doesn't contain value with rethinkDB
I'd like to append a value to an array in a record that looks similar to the following: 我想在类似于以下内容的记录中向数组添加一个值:
{
_id: 'foo',
cols: [
'abc123',
'123abc'
]
}
It's possible that this field doesn't exist and will need to be created prior to appending. 此字段可能不存在,需要在添加之前创建。 I also don't want to append to the array if the value already exists in the array.
我也不想附加到数组,如果值已经存在于数组中。 So far I have the following which satisfies all but the last requirement of not adding duplicate entries.
到目前为止,除了满足不添加重复条目的最后一个要求之外,我的所有内容都可以满足以下要求。
r.table('users')
.get(userId)
.update({
cols: r.row('cols').default([]).append(uuid)
})
Any help appreciated, thanks! 任何帮助表示赞赏,谢谢!
You have several solutions. 您有几种解决方案。
r.table('users')
.get(userId)
.update({
cols: r.branch(r.row('cols').default([]).contains(uuid),
r.row('cols'),
r.row('cols').default([]).append(uuid))
})
Or we can use setInsert
as @char suggestions 或者我们可以将
setInsert
用作@char建议
r.table('users')
.get(userId)
.update({
cols: r.row('cols').default([]).setInsert(uuid))
})
The issue with setInsert
is it ensure returning a set. setInsert
的问题在于它确保返回一个集合。 So if you have intentinally put duplicate elements in original cols
, it will remove dup element. 因此,如果您有意将重复的元素放在原始
cols
,它将删除dup元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.