如何仅在数组没有的情况下追加到数组't包含带有rethinkDB的值

How to append to array only if it doesn't contain value with rethinkDB

本文关键字:数组 包含带 的值 rethinkDB 追加 何仅 情况下      更新时间:2023-09-26

我想将一个值附加到一个记录中的数组中,该记录看起来类似于以下内容:

{
  _id: 'foo',
  cols: [
    'abc123',
    '123abc'
  ]
}

这个字段可能不存在,需要在追加之前创建。如果数组中已经存在值,我也不想追加到数组中。到目前为止,我有以下内容,它满足了除最后一项要求外的所有要求,即不添加重复条目。

r.table('users')
 .get(userId)
 .update({
   cols: r.row('cols').default([]).append(uuid)
 }) 

感谢任何帮助,谢谢!

您有几个解决方案。

r.table('users')
 .get(userId)
 .update({
   cols: r.branch(r.row('cols').default([]).contains(uuid),
                   r.row('cols'),
                   r.row('cols').default([]).append(uuid))
 }) 

或者我们可以使用setInsert作为@char建议

r.table('users')
 .get(userId)
 .update({
   cols: r.row('cols').default([]).setInsert(uuid))
 }) 

setInsert的问题是它确保返回一个集合。所以,如果您有意在原始cols中放置重复的元素,它将删除dup元素。