0

I have a document that looks similar to the following

{
  ...
  reactions: [
    {
      user: 'user_id',
      reaction: 'reaction_name'
    }, {
      user: 'user_id',
      reaction: 'reaction_name'
    }
  ]  
  ...
}

I'm trying to remove an item in the array reactions based on a combination of 'user' and 'reaction' which will be unique. How would I go about filtering the reactions array to remove that specific item in rethinkdb using the js driver?

I've tried this

r.db('db_name').table('messages').getAll(
                        get_single_message
                      ).update({
                        reactions: r.row('reactions').filter( (item) => {
                           return item('reaction').ne(body.reaction).and(item('user').ne(body.user))
                        })
                      }).run(this._rdbConn)

I understand why it doesn't work (returns all reactions that don't have given reaction, then returns subset of that array that doesn't have certain user). What I want is for those not equals to be performed in sync so it returns an array that doesn't include items that have the provided reaction AND user. Right now it functions more like reaction OR user.

millejo3
  • 13
  • 3

2 Answers2

0

A buddy helped me out. Here's a solution that works for what I was trying to accomplish, but it does not makes use of not equal. If anyone has another solution that makes use of not equal please share it.

r.db('db_name').table('messages').getAll(
                        get_single_message
                      ).update({
                        reactions: r.row('reactions').filter(function (doc) {
                             return doc('reaction').eq(body.reaction).and(doc('user').eq(body.user)).not()
                         })
                      }).run(this._rdbConn)
millejo3
  • 13
  • 3
0

Here's a possibly more simplified way to do this without .ne:

r.db('db_name').table('messages').getAll(
                        get_single_message
                      ).update({
                        reactions: r.row('reactions').difference([{
                          reaction: body.reaction,
                          user: body.user
                        }])
                      }).run(this._rdbConn)

Just be warned that .difference will remove all instances of that object from the array, so this assumes that there are only single instances of unique combinations of reaction and user.

Or you could keep it closely to what you have already and use the different form of .and()

...
reactions: r.row('reactions').filter( (item) => {
                           return r.and(item('reaction').ne(body.reaction), item('user').ne(body.user))
                        })
...
dalanmiller
  • 3,467
  • 5
  • 31
  • 38