How can I write a RethinkDB query for a document which returns a merged version of the document if it is found, and null
otherwise?
The following, naive, query (written in JavaScript) causes an exception to be thrown from .merge
in case .get
returns null
(ie the user isn't found):
r.table('users')
.get(username)
.merge((user) => {
return {
'projects': r.table('projects').getAll(username, {index: 'owner',})
.coerceTo('array'),
}
})
.run(conn)
Writing a merge query, while handling the case where a document is not found, can be accomplished through the use of do
and branch
, so that merge
only gets invoked on non-null results:
r.table('users')
.get(username)
.do((user) => {
// Only perform a merge if user isn't null
return r.branch(
user.eq(null),
null,
user.merge({
'projects': r.table('projects').getAll(username, {index: 'owner',})
.coerceTo('array'),
})
)
})
.run(conn)
您可以在合并查询之后添加.default(null)
来处理不存在的错误(尽管这也将处理合并查询中的任何其他不存在的错误)。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.