Thiện Nguyễn
Thiện Nguyễn

Reputation: 41

How to populate in RethinkDB

I have 2 RethinkDB Table:

Left: 
{
  id: String,
  title: String,
  key: String // for mapping with table Right
}

Right:
{
 id: String
 title: String
 description: String
}

RethinkDB has eqJoin() and zip() method, which help us clone all field of table Right to table Left:

r.db("myDB").table("Left")
.eqJoin("key", r.db("myDB").table("Right"))
.zip()

The result will look like this:

[{
  id: "the-id",
  key: "Right-object-id",
  title: "Title of Right Object",
  description: "Description of Right Object"
  // => title of Left Object was deleted
}]

The question is: How to simulate a query like populate() of Mongoose?

I want a result look like this:

[{
  id: "the-id",
  key: {
     id: "Right-object-id"
     title: "Title of Right Object"
     description: "Description of Right Object"
  }
}]

Upvotes: 2

Views: 327

Answers (3)

Jorge Silva
Jorge Silva

Reputation: 4614

Using eqJoin

You can map the result, using eqJoin:

r.db("myDB").table("Left")
.eqJoin("key", r.db("myDB").table("Right"))
.map(function (row){
  return row('left').merge({ key: row('right') })
})

Sub Queries

While you can use eqJoin in RethinkDB, subqueries are usually easier to work with and more powerful. You can use the merge term to add a new key and then use a subquery to set the value of that key:

r.db("myDB").table("Left")
.merge(function (row){
  return {
    'key': r.db("myDB").table("Right")).get(row('key'))
  }
})

I usually never use eqJoin. It's not as easy to work with as just using subqueries.

Upvotes: 6

kureikain
kureikain

Reputation: 2314

I'm not sure if you consider following is a better solution because I don't see what wrong with your query, as long as you use index, the query is fast and efficient.

r.db('myDB').table("Left").map(function (doc) {
   return doc.merge({key: r.db('myDB').table('Right').get(doc('key'))})
})

This query, however, always use primary index on right table, by default, because we use get

Upvotes: 0

Thiện Nguyễn
Thiện Nguyễn

Reputation: 41

This is a solution, but I'm finding a better solution than it:

r.db('myDB').table("Left").eqJoin("Right",r.db("myDB").table("Right"))
.map(function(row){
  return row("left").merge({key: row("right")})
})

Upvotes: 0

Related Questions