简体   繁体   English

如何仅在rethinkDB中不包含值的情况下追加到数组

[英]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.

相关问题 Rethinkdb追加到数组(如果存在) - Rethinkdb append to array if exists RethinkDB-多边形不接受顶点数组吗? - RethinkDB - Polygon Doesn't Accept an Array of Vertices? 仅在数组中不存在项目时附加 - Append only if item doesn't exists in array Rethinkdb Append说属性不存在 - Rethinkdb Append says attribute doesn't exist when it does 比较一个数组与另一个数组以确保第二个数组不包含其他值 - compare one array to another to make sure the second doesn't contain a different value 仅当值不存在时才使用 lodash 推送到数组? - Using lodash push to an array only if value doesn't exist? 如果div元素不包含文本且只有<br>元素,如何选择和删除它? - How to select and remove a div element if it doesn't contain text and only has <br> elements? 如何仅使用正则表达式匹配不包含特定单词的字符串范围? - How to match a range of string that doesn't contain an specific word using only regular expression? 如何从不包含搜索关键字的字符串数组中删除字符串? - How to remove strings from an array of strings which doesn't contain search keyword? 如果数组不存在,则循环遍历对象数组和 append 和 Object 到数组 - Loop through Array of Objects and append the Object to an Array if it doesn't exist
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM