Rethinkdb create if not exists

732 views Asked by At

What I'm trying to do is the following:

  1. Check if a record with a filter criteria exists
  2. If it does, do nothing
  3. If it does not, create it with some default settings.

Now I could do it with 2 queries:

function ensureDocumentExists(connection, criteria, defaults) {
  return r.table('tbl')
    .filter(criteria)
    .coerceTo('array') // please correct me if there's a better way
    .run(connection)
    .then(([record]) => {
      if (record) {
        return Promise.resolve() // Record exists, we are good
      } else {
        return r.table('tbl') // Record is not there we create it
          .insert(defaults)
          .run(connection)
      }
    })
}

But the fact that r.branch and r.replace exists, suggest me that this would be possible in a single run. Is it? I was thinking something like this:

function ensureDocumentExists(connection, criteria, defaults) {
  return r.table('tbl')
    .filter(criteria)
    .replace(doc => r.branch(
      r.exists(doc), // If doc exists (I'm just making this up)
      doc, // Don't touch it
      defaults // Else create defaults
    )).run(connection)
}

But I'm not sure if replace is the right method for this, and also no idea how to check if the given row exists.

1

There are 1 answers

0
Balázs Édes On BEST ANSWER

Figured it out:

function ensureDocumentExists(connection, criteria, defaults) {
  return r.table('tbl')
    .filter(criteria)
    .isEmpty() // isEmpty for the rescue
    .do(empty => r.branch(
      empty, // equivalent of if(empty)
      r.table('tbl').insert(defaults), // insert defaults
      null // else return whatever
    ).run(connection)
  })
}