Using Rxjs for MongoDB Document References: A Step-by-Step Guide

Currently, I am working on an app using Ionic2/rc0. In my singleton service, I have a ReplaySubject that maintains the consistency of the current user throughout the entire application. Everything is functioning properly, and I can easily subscribe to it and retrieve a User object with the following code:

this._user.Current.subscribe(user=>{ console.log(user)});

The structure of the User object is as follows:

User {
    confirmed:true,
    devices:["57f65werwe343bn8843f7h","7yr3243h5429hf2hjd"],
    friends:["t245y53h65346htyh","356ytrer75dfhg43we56df"],
    email:"[email protected]",
    id:"57f6525e926bbc7615fc5c5c",
    notification:false,            
    password="$2a$04$.Fk/8eMj18ZrkfurbbdP4uT3yOs7Lb9db74GkNfgtABVY.ez2Q0I.",
    picture:"https://api.cescoferraro.xyz/kitty",
    role:"master",
    username:"cesco"
}

My backend setup involves MongoDB with One-to-Many Relationships utilizing Document References, which is detailed here.

I have a "devices" tab where I aim to display all information related to the user's devices. However, I need to iterate through each of the "current.devices" by calling this._devices.info for each one and then combining the results into TrueDevices.

@Component({
    template: `  
            <ion-header>
                <ion-navbar>
                    <ion-title>Tabs</ion-title>
                </ion-navbar>
            </ion-header>
            <ion-content>
                <h2>Device:list</h2>

                <h2 *ngFor="let item of devices | async">{{item}}</h2>

                <button ion-button (click)="readDevice()">Read Random Device</button>
            </ion-content>
`
})
export class DeviceComponent {
    devices: Observable<string[]>;
    TrueDevices: Observable<Device[]>;

    constructor(public _user: UserService, public _device: DeviceService) {

        this._user.Current.subscribe(user=>{ this.devices = Observable.of(user.devices)});

        // Get current User
        // call this._devices.info for each one of current.devices
        // concat the result back to TrueDevices
        this._user.Current
            .subscribe((result) => { console.log(result) });

    }

    readDevice(){
        console.log(this.devices);
        this._device.info(this.devices.value[0]).subscribe(data=>console.log(data))
    }
}

A similar procedure will be followed for the friends' tab and other tabs. While I believe there are certain operators in rxjs that could simplify this process, I am relatively new to rxjs and not well-versed in all its functionalities. Can anyone suggest the best approach?

Answer №1

this._user.Current
  .switchMap(user => Observable.from(user.devices)) // transformed into an Observable<string> after this line
  .mergeMap(device => this._device.info(device)) // each device will be associated with another observable(or stream), and all the streams will be merged together
  .toArray() // all streams are awaited to complete and results are reduced into an array.
  .subscribe(array => console.log(array));

or visit the gitter room: https://gitter.im/Reactive-Extensions/RxJS

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular application navigation does not work as expected when the application is served in Express.js

I have an Angular 7 application that is running on an ExpressJS server. This is how the server part of the app is set up: app.get('/', (req, res) => { console.log(`sending...`); res.sendFile(path.join(__dirname, 'index.html') ...

Node.js and MongoDB query does not return any results

I'm facing an issue with retrieving data from MongoDB using the find() method. Even though there is data in the collection, I'm getting no results. I'm unable to identify the cause of this problem, can someone assist me? Here's the exp ...

Issues with Angular 2 loading properly on Internet Explorer 11

We are currently running an Asp.net MVC 5 web application integrated with Angular 2. The application functions smoothly on Chrome, Firefox, and Edge browsers, but encounters loading issues on IE 11, displaying the error illustrated in the image below: ht ...

Delete Entries in MongoDB Collection According to Unique User Pairs

I have a collection of messages stored in MongoDB and I need to keep only the latest 500 records for each pair of users. Users are identified by their sentBy and sentTo attributes. /* 1 */ { "_id" : ObjectId("5f1c1b00c62e9b9aafbe1d6c&quo ...

What is the best way to conceal the parent ul when at the li level?

html component <div class="select-wrapper select"> <input (click)="toggleOptionsView()" type="text" class="select-dropdown" data-activates="select-options-524f0174-3e9b-445a-8bf3-e304572eb476" value="Choose your option"> <ul [n ...

Angular 6 combined with Firebase is experiencing difficulties with routing after a successful login

After spending hours trying to fix my issue, I still can't figure it out. I've searched through related threads on SO, but haven't found a solution yet. Issue After successfully signing up, the email verification flag is set to true. Howev ...

Guide on refreshing an Angular 2 application after a user has logged out

Is there a way to refresh my Angular 2 application once a user clicks on the logout button? I want all current data in the app to be cleared and then load a sign-in form from the server. Currently, when I click on the logout button, I receive the response ...

Having trouble choosing multiple options from autocomplete drop-down with Selenium web-driver in Python

I am currently in the process of automating a webpage built with Angular that features an auto-complete dropdown with numerous elements. My goal is to click on each individual element and verify if it populates all the fields below accordingly. Below is th ...

Why does the Change Detection problem persist even when using On Push with the same object reference?

After a recent discussion on Angular Change detection, I believed I had a solid understanding. However, my confidence wavered when I encountered this issue: Why is change detection not happening here when [value] changed? To further illustrate the problem ...

Error: JSON parsing error - Unexpected token at the start of the JSON data when using JSON.parse() function

Backend code router.route('http://localhost:5007/api/media') .post(mediaCtrl.saveMedia) async saveMedia(req, res) { let file = req.files.file let ext = req.body.extension let path = req.body.path if(_.isNull(file) || _.isEmp ...

Tips for crafting a test scenario for input alterations within Angular

Hello there, currently I am working on an application using Angular and TypeScript. Here is a snippet of my template code: <input type="text" placeholder="Search Results" (input)="searchInput($event)"> And here is the TypeScript code for the searc ...

Find and return a specific record from MongoDB if it matches the exact value

model.js import mongoose from 'mongoose'; const { Schema, Types } = mongoose; const participants = { user_id: Types.ObjectId(), isAdmin: Boolean } const groupSchema = new Schema({ id: Types.ObjectId(), // String is shorthand for {type: St ...

Having difficulty resolving all parameters for the component: (?, [object Object]) in the Jasmine component Unit Test

While defining a UT for a component with an extended class using i8nService and ChangeDetectionRef, I encountered an error preventing me from instantiating it: Failed: Can't resolve all parameters for BrandingMultiselectComponent: (?, [object Object] ...

How can I retrieve the height of a dynamically generated div in Angular and pass it to a sibling component?

My setup consists of a single parent component and 2 child components structured as follows: Parent-component.html <child-component-1 [id]="id"></child-component-1> <child-component-2></child-component-2> The child-compo ...

Having trouble with submitting data in an ExpressJS POST request while using mongoose?

As I embark on building my first express.js application, I encounter my initial obstacle. The setup is rather simple. Routes in app.js: app.get('/', routes.index); app.get('/users', user.list); app.get('/products', product. ...

ngRepeat does not iterate through an array

Presented below is an object: { "_id" : ObjectId("5454e173cf8472d44e7df161"), "questionType" : 0, "question" : "question1", "answers" : [ { "content" : "answer1" }, { "is_true" : "true", ...

JHipster's selection of radio button options

Within a jhipster project, I have an Enumeration field containing values "A, B, C, D, E". The conventional approach in Jhipster utilizes a Select/Options setup: <div class="form-group"> <label class="form-control-label" jhiT ...

Unexpected behavior with Angular 10 behavior subject - encountering null value after invoking .next(value) function

Can anyone help me solve the mystery of why my user value turns null after I log in? This is the login page where an API is called and the result is obtained as shown below: https://i.stack.imgur.com/kDjSy.png Here is the authentication service implemen ...

A step-by-step guide on customizing the background color of a Dialog in Angular Material (Version 16)

I've been attempting to modify the background color of my Angular Material Dialog by utilizing the panelClass property in the MatDialogConfig. Unfortunately, I'm encountering a partial success. I am aiming to set the background color as red (jus ...

Sidenav Angular Material cdkScrollable is an effective tool for creating scrollable

In Angular Material CDK, there is a special Directive called CdkScrollable that allows you to monitor ScrollEvents within a specific container. I am currently attempting to retrieve the CdkScrollable associated with the default MatSidenavContent. Unfor ...