I have an .itemId
which comes from a 3rd party, not generated by me.
I need to look for it in the db and update or insert it if one doesn't exist.
I've tried using this example from the cookbook: https://www.rethinkdb.com/docs/cookbook/javascript/#manipulating-documents
const res = await this.r.table('products').filter({itemId: item.itemId})
.limit(1)
.replace(doc => {
return this.r.branch(
doc.eq(null),
this.r.expr(item).merge({created_at: this.r.now()}),
doc.merge(item).merge({updated_at: this.r.now()})
)
}, {
returnChanges: true
}).run(this.conn);
if (res.replaced) {
return res.changes[0].new_val;
} else {
return item; // doc was never inserted as everything in `res` is `0`.
}
res.changes
is undefined if the doc doesn't exist and if I search for the id after it is not in the database. It never got inserted.
Is there a way to simplify upsert()
command given an arbitrary property of an object?