RethinkDB: Fixing error “e: No attribute `last_name` in object:”

If you run a ‘map’ in RethinkDB and an attribute is not found, you can get an error like so:

r.db('test')
 .table('users')
 .map(
  (doc) => {
    return {
      first_name: doc('first_name'),
      last_name: doc('last_name')
    }
  }
)
e: No attribute `last_name` in object:

There are a couple ways to fix this, depending on your needs.

You can remove objects without these attributes:

r.db('test').table('users')
  .withFields(['first_name', 'last_name'])
  .map(
    (doc) => {
      return {
        first_name: doc('first_name'),
        last_name: doc('last_name')
      }
    }
  )

You can also fix this by setting default attributes with the ‘merge’ function (this is similar to coalesce in SQL):

r.db('test').table('users')
  .map(
    (doc) => { return r.expr(
      {
        first_name: '',
        last_name: ''
      }
    ).merge(doc) }
  )