我有2个RethinkDB表:
Left:
{
id: String,
title: String,
key: String // for mapping with table Right
}
Right:
{
id: String
title: String
description: String
}
RethinkDB有eqJoin()和zip()方法,它帮助我们克隆表的所有字段对表左:
r.db("myDB").table("Left")
.eqJoin("key", r.db("myDB").table("Right"))
.zip()
结果如下:
[{
id: "the-id",
key: "Right-object-id",
title: "Title of Right Object",
description: "Description of Right Object"
// => title of Left Object was deleted
}]
问题是: 如何模拟 Mongoose 的 populate()等查询?
我希望结果如下:
[{
id: "the-id",
key: {
id: "Right-object-id"
title: "Title of Right Object"
description: "Description of Right Object"
}
}]
答案 0 :(得分:5)
使用eqJoin
您可以使用eqJoin
:
r.db("myDB").table("Left")
.eqJoin("key", r.db("myDB").table("Right"))
.map(function (row){
return row('left').merge({ key: row('right') })
})
子查询
虽然您可以在RethinkDB中使用eqJoin
,但子查询通常更易于使用且功能更强大。您可以使用merge
术语添加新密钥,然后使用子查询来设置该密钥的值:
r.db("myDB").table("Left")
.merge(function (row){
return {
'key': r.db("myDB").table("Right")).get(row('key'))
}
})
我通常不会使用eqJoin
。使用子查询并不容易。
答案 1 :(得分:0)
这是一个解决方案,但我找到了比它更好的解决方案:
r.db('myDB').table("Left").eqJoin("Right",r.db("myDB").table("Right"))
.map(function(row){
return row("left").merge({key: row("right")})
})