0

I'm building a simple marketplace web app where the user posts their products. I want to get the user owner of each product. Please tell me how do I perform Firebase inner joins using observables!

 productsRef: AngularFireList<any>;

  ///
 constructor(
    private db: AngularFireDatabase,
    private userService: UserService

  ) {
    this.productsRef = db.list('/products');
  }

getProductsList() {
    const product$ = this.productsRef.valueChanges();
    // 1st observable to get the products
    const productsResults$ = product$.pipe(
      switchMap(products => products)
      )
    );

    productsResults$.subscribe(
      console.log,
      console.error,
      () => console.log('completed httpResult$')
    );

   // 2nd observable  to get the user 
    const user$ = this.userService.getUserById(Id);

    productsResults$.subscribe(
      console.log,
      console.error,
      () => console.log('completed httpResult$')
    );

}

i get the 2 following results.

Products

[
  {
    "key": "-TM2Y6vBk70rgKZ3zTUAw",
    "name": "T-shirt",
    "size": "M",
    "user": "-NDNPe47CDTbjmwGgW_3",
  }, 
]

User


  {
    "key": "-NDNPe47CDTbjmwGgW_3",
    "username": "Alex199",
  }, 

the end result i want

{
    "key": "-TM2Y6vBk70rgKZ3zTUAw",
    "name": "T-shirt",
    "size": "M",
    "user": {
       "key": "-NDNPe47CDTbjmwGgW_3",
        "username": "Alex199",
     }, 
},

How can I achieve this using observable?

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
Sb Zakaria
  • 311
  • 6
  • 18
  • no answer again.... – Sb Zakaria Oct 09 '22 at 15:16
  • What do you mean by "inner join"? What is the exact your you want to perform? – Alex Mamo Oct 10 '22 at 07:28
  • Inner join, like in SQL. i want ti link the corresponding user in the product object by his key. so i take the user key from the product object , go to the user list fetch the user with that key and then join it to the product object ! – Sb Zakaria Oct 10 '22 at 10:15

1 Answers1

0

There is no Inner Join clause in NoSQL databases. So if you want to read some data at a location based on what you read at another location, then you have to perform two separate requests. There is no way you can get that data in a single go.

Alternatively, if you don't want to perform two separate queries, then you can save user data right inside the product node, or vice versa. This practice is called denormalization and is a common practice when it comes to NoSQL databases like Realtime Database. For a better understanding, I recommend you see this video.

If you consider at some point in time try using Cloud Firestore, then I recommend you read my answer from the following post:

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193