Ways to recover information that is not typically found

My firebase database has two main trees: "tag" and "user". Each user is associated with a set of tags, referred to as preferences. Here is the structure of my database:

https://i.sstatic.net/m98EO.jpg

I am trying to display a list of preferences that a specific user does not have.

Example: 
Tags: 1, 2, 3, 4
User has preference 1 and 3 
I want to display in a list: 2 and 4!

I have successfully implemented code to show all the preferences/tags that the user has. However, I am struggling to figure out how to display a list of what the user doesn't have!

Below is the code that accurately displays the common preferences (which is currently working correctly)

showUserPreferences(){

   let userTag = [];
   var ref = firebase.database().ref('/users/'+ this.email+'/preferenze/') 
   var ref1 = firebase.database().ref('/tag/');
   ref.once('value', function(preferenze){ 
     preferenze.forEach(function(singolaPref){
       ref1.once('value', function(tags){ 
        tags.forEach(function (singoloTag){ 
           if(singolaPref.key == singoloTag.key){ 

           userTag.push(singolaPref.child("nome").val()) 
           }
           return false;
         })
       })
       return false;
     })

   }).then(a=>{
       this.tags = userTag;
     }) 
}

I hope I have clearly explained my issue. Feel free to ask for more code or details if needed. Thank you in advance.

Answer â„–1

Feeling inspired, I decided to share an answer accompanied by a rough code example.

The concept involves loading both snapshots—the collections labeled preferences and tag. It's possible to store the preferences in a map for quick reference. Later, this map can be utilized when cycling through the tags.

showMissingPreferences() { 
    var preferencesRef = firebase.database().ref('/users/'+ this.email+'/preferences/') 
    var tagsRef = firebase.database().ref('/tag/');

    preferencesRef.once('value')
        .then(userPrefSnap => {

            // Storing the user's tags in a map for easy lookup.
            let userPrefMap: { [key: string]: boolean } = {}
            userPrefSnap.forEach(userTagSnap => {
                userPrefMap[userTagSnap.key] = true
            })

            return tagsRef.once('value')
                .then((tagsSnap) => {
                    let missingTags = []
                    tagsSnap.forEach(tagSnap => {
                        // Add the tag only if it's not already in the map.
                        if(!userPrefMap[tagSnap.key]) {
                            missingTags.push(tagSnap.child("name").val())
                        }
                    })
                    return missingTags
                })
        })
        .then(missingTags => {
            this.tags = missingTags
        })
}

I haven't executed or tested the code, so there may be mistakes present. Nonetheless, the core idea should still come across!

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

What are the consequences of relying too heavily on deep type inference in React and Typescript?

In the process of migrating my React + Javascript project to Typescript, I am faced with preserving a nice unidirectional flow in my existing code. The current flow is structured as follows: 1. Component: FoobarListComponent -> useQueryFetchFoobars() 2 ...

How do I implement branch code using TypeScript types in Svelte?

Looking for a solution similar to the one mentioned in Typescript: How to branch based on type, but tailored for Svelte. Despite implementing run-time type guards as suggested, Svelte continues to throw errors. I am dealing with an array called collectabl ...

Increasing the number of service providers in Angular2-4 directives

Is there a way to apply both * to a string? Below is the code snippet I am working with: <a class="sidenav-anchor" *ngIf="!item.hasSubItems()" md-list-item md-ripple [routerLink]="[item.route]" routerLinkActive="active" [routerLinkActiveOptions]="{ex ...

How do @material-ui/core and @types/material-ui interact with each other?

Exploring a sample project that utilizes material-ui. Upon inspecting the package.json file, I noticed the inclusion of the following packages: { ... "dependencies": { "@material-ui/core": "^1.4.1", ... }, "devDependencies": { "@types ...

Error message: "Declared app-routing module in Angular 2 is encountering routing declaration

Currently, I am immersing myself in learning Angular 2 through the official tutorial available at https://angular.io/docs/ts/latest/tutorial/toh-pt5.html. However, I have encountered an issue related to routing. The error message displayed states: Type Das ...

Can you explain the distinction between using [ngFor] or [ngForOf] in Angular 2?

From what I gather, both serve the same purpose. However, ngFor operates similar to collections. ngForOf functions more like generics. Am I correct in my understanding? Or can you provide more insight on the differences between ngFor and ngFor ...

In what scenario would one require an 'is' predicate instead of utilizing the 'in' operator?

The TypeScript documentation highlights the use of TypeGuards for distinguishing between different types. Examples in the documentation showcase the is predicate and the in operator for this purpose. is predicate: function isFish(pet: Fish | Bird): pet ...

Issue with uploading image to Firebase Storage in Swift 5

I am facing an issue with uploading an image to Firebase Storage. The error message in my output log reads as follows: "An SSL error has occurred and a secure connection to the server cannot be made." Additionally, the final output message is: pri ...

Discovering Type Definitions in Nuxt.js Project Without Manual Imports in VSCode: A Step-by-Step Guide

Having issues with VSCode not recognizing type definitions automatically in a Nuxt.js project with TypeScript. I'm looking to avoid manually importing types in every file. Here's my setup and the problem I'm facing: Configuration My tsconfi ...

What steps should I take to choose esNext from the typescript menu within visual studio 2017?

When utilizing dynamic import with TypeScript in Visual Studio 2017, I encountered the following error: TS1323(TS) Dynamic imports are only supported when the '--module' flag is set to 'commonjs' or 'esNext'. I attempted to c ...

Inferencing partial types in Typescript

I'm completely stuck on this and can't seem to figure it out without using a second function: interface Fixed { a: number } const fn = <A, B extends {} = {}>(b: B) => { return b } fn({ a: 1 }) // { a: number } fn<Fixed>({ a: 1 } ...

Angular2 - Actively selecting a checkbox in an ngFor loop with a reactive form

There is an object retrieved from a database that consists of a list of names with their corresponding IDs, as well as a flag to indicate whether they are selected or not. Object: let items = [{ ID: 1, Name: 'Item A', Selected: 'Y ...

Decipher and comprehend the buttons listed in the language translation document

Looking for assistance with a pipe issue. I've created the following custom SafeHtmlPipe: import { DomSanitizer } from '@angular/platform-browser'; import { Pipe, PipeTransform, SecurityContext } from '@angular/core'; @Pipe({ nam ...

Using TypeScript will result in errors when attempting to use the Promise object and the Awaited keyword

In this example, I am trying to ensure that the function foo does not accept a Promise as an argument, but any other type should be acceptable. export {} function foo<T>(arg: T extends Promise<unknown> ? never : T) { console.log(arg); } asy ...

Differences between Typescript, Tsc, and Ntypescript

It all began when the command tsc --init refused to work... I'm curious, what sets apart these three commands: npm install -g typescript npm install -g tsc npm install -g ntsc Initially, I assumed "tsc" was just an abbreviation for typescript, but ...

Chrome fails the karma tests while phantomjs passes them

I've been struggling with this issue for some time now and can't seem to find a solution. I'm working on an Ionic 2 project that utilizes Angular 2's testing environment. When I run 'ng test' using Karma's Chrome launcher ...

Using Angular 4 Component to Invoke JavaScript/jQuery Code From an External File

I have written a jQuery code that is executed at ngAfterViewInit(). //myComponent.ts ngAfterViewInit() { $(function () { $('#myElement').click(function (e) { //the code works fine here }); } However, I want t ...

Using Angular, a function can be called recursively directly from within the HTML

I'm struggling with loading an image because the method getUserProfileImage() is getting triggered multiple times within a loop. Is there a way to ensure the method is only called once during each iteration? I understand that this issue is related to ...

Tips for finalizing a subscriber after a for loop finishes?

When you send a GET request to , you will receive the repositories owned by the user benawad. However, GitHub limits the number of repositories returned to 30. The user benawad currently has 246 repositories as of today (14/08/2021). In order to workarou ...

Can you explain the distinction between employing 'from' and 'of' in switchMap?

Here is my TypeScript code utilizing RxJS: function getParam(val:any):Observable<any> { return from(val).pipe(delay(1000)) } of(1,2,3,4).pipe( switchMap(val => getParam(val)) ).subscribe(val => console.log(val)); ...