What I'm trying to do is the following:
- Check if a record with a filter criteria exists
- If it does, do nothing
- 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.
Figured it out: