Search code examples
rethinkdbrethinkdb-javascriptreql

RethinkDB: Check if object in array exist and replace it


I have this JSON document:

{
  userId: xx,
  followedAuthors: [
    { authorId: abc, timestamp: 123 },
    { authorId: xyz, timestamp: 456 },
  ]
}

When a user want to follow an author I would like to write a query that check if that author is already followed, checking the id, and if it's not append the new followed author to the array.

Right now I create everytime a new entry. This is my query:

r.table('users')
 .get(userId)
 .replace(user => {
   return user.merge({
     followedTopics: user('followedTopics')
        .default([])
        .setInsert({ topic: topic, timestamp: now }),
     })
  })

Solution

  • The best way to implement this is to use contains (using a predicate function), branch, and append.