Unable to fetch document from firestore using .doc()

I have a collection whose document id got changed.

Now when I fetch that document using this piece of code:

const doc = database.collection(col).doc(col.documentId as string);

I get this error:
Error: 5 NOT_FOUND:

But if I use the where clause and provide the same col.documentId, I am able to fetch that document.

Please help here.

“TypeError: Cannot read properties of undefined (reading ‘onDestroy’)” while using observable with NgFor and the Async Pipe

I’m trying to display a list of jobs, the code looks like

 loadJob() {
   let query = { pageNo: this.pageNo, title: this.searchParam.title, location: this.searchParam.location, industry:this.searchParam.industry }
   this.store.dispatch(InitJobComponent({query}));
   this.jobs$ = this.store.pipe(
     select(getJobState)
   );
   
   this.jobs$.subscribe((jobs) => {
     if (jobs && jobs.data && jobs.data.length>0) {
       this.currentJob = jobs.data[0];
       this.checkSaveStatus(this.currentJob);
       this.trustedUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.currentJob.file);
     }
   });
 }
<div *ngIf="(jobs$ | async) as jobs" class="page-wrapper job-list">
  <div class="no-results" *ngIf="jobs.totalCount == 0">
    <h3>No results found.</h3>
  </div>
  <nz-layout *ngIf="jobs.totalCount > 0" class="content">
    <nz-sider class="side-bar-job-list">
      <ul class="jobs" nz-menu nzMode="inline">
        <li nz-menu-item *ngFor="let job of jobs.data; let i=index" (click)="details(job);">
          <!-- whatever the code is to display the list -->
        </li>
      </ul>
      <nz-pagination [nzPageIndex]="pageNo" (nzPageIndexChange)="paginate($event);" [nzTotal]="jobs.totalCount">
      </nz-pagination>
    </nz-sider>
  </nz-layout>
</div>

I get the error ERROR TypeError: Cannot read properties of undefined (reading 'onDestroy') where I’m trying to use *ngFor. I can’t figure out why this is happening, please help.

onclick not firing from laptop mousepad ‘tap/touch’, working with LEFT click of mousepad

Hi Sorry if this sounds confusing but I have an issue involving the ‘onclick’ event of a dropdown list li> elements. The onclick function specified works correctly when clicking the mouse LEFT button, but when I use my laptop and ‘tap’ the mousepad to click instead of using the LEFT mousepad button the onclick even does not fire?
I create the list via a for loop and then add to the ul> elements html

for (var i = 0; i < accountListData.length; i++) {
                        if(accountListData[i]['ACCOUNTCODE'].toUpperCase().trim().includes(txt.toUpperCase().trim()) || accountListData[i]['ACCOUNTNAME'].toUpperCase().trim().includes(txt.toUpperCase().trim())) {
                            s += '<li onclick="selectAccount(this, ' + "'" + accountListData[i]['UseRatesFromAccount'].trim() + "'," + "'" + accountListData[i]['ACCOUNTNAME'].replaceAll("'", "").trim() + "'," + "'" + accountListData[i]['subAccounts'] + "'," + "'" + accountListData[i]['ACCOUNTCODE'] + "'" + ')" class="account-quick-search-item" value="' + accountListData[i]['ACCOUNTCODE'] + '">' + '<div style="' + 'font-size: 11px;font-weight: bolder;">' + accountListData[i]["ACCOUNTCODE"] + '</div><div style="' + 'margin-left: 6px; margin-top: 2px;' + '">' + accountListData[i]["ACCOUNTNAME"] + '</div>';
                            if (accountListData[i]['subAccounts'] == "1") {
                                s = s + '<div class="sub-account-icon"></div>' + '</li>';
                            }
                            else {
                                s = s + '</li>'
                            }
                            if (i != (accountListData.length - 1)) {
                                s += '<li class="account-quick-search-divider"></li>';
                            }
                        }
                    }
                    $("#accountsQuickSearch").html(s);

Any help would be appreciated, is the mousepad/touchpad of a laptop a different type of click event for the ‘tap’ type of click?

Is there a way to update Firebase Firestore Security Rules when creating new user from Admin SDK

I am trying to create a new user that will be associated with an email from a user previously logged in to the website. I receive an email from that user, and I want to give that user with that phone number access to the collection that the logged-in user also has on the website. My current rules are:

  match /databases/{database}/documents {
       match /{userEmail}/{document=**} {
      allow read, write: if request.auth != null && request.auth.token.email == userEmail;

app.post('/createUser', (req, res) => {
  const phoneNumber = req.body.phoneNumber;

  admin.auth().createUser({
    phoneNumber: phoneNumber
  })
  .then((userRecord) => {
    // User created successfully. Get the UID from the userRecord.
    const uid = userRecord.uid;

  })
  .catch((error) => {
    console.log('Error creating new user:', error);
    res.status(500).send('Error creating user');
  });
});

Ionic Vue header menu loses click outside events with IonRouterOutlet

I am creating a small Ionic-Vue app and im putting the header with a menu in its own component so i can simply re-use the header on each route. This works but with one issue, this seems to cause the click events to break when i give the content-id prop the id of the IonRouterOutlet. When i duplicate the menu on each SPC it works as expected but moving it to the IonRouterOutlet as the docs suggest, causes issues.

**Ionic 5
**Ionic Framework 7

App.vue

<template>
  <IonApp>
    <IonRouterOutlet id="main-content" />
  </IonApp>
</template>

<script setup lang="ts">
import { IonApp, IonRouterOutlet } from '@ionic/vue';
</script>

Header.vue

<template>
  <ion-menu side="end" content-id="main-content">
    <ion-header>
      <ion-toolbar>
        <ion-title><slot></slot></ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content class="ion-padding">This is the menu content</ion-content>
  </ion-menu>

  <ion-header>
    <ion-toolbar :color="color">
      <ion-title>{{ props.title }}</ion-title>
      <ion-buttons slot="end">
        <ion-menu-button></ion-menu-button>
      </ion-buttons>
    </ion-toolbar>
  </ion-header>
</template>

any SPC that consumes Header.vue

<template>
  <IonPage>
    <Header title="Home"></Header>

    <IonContent class="ion-padding">
        <!-- stuff here... -->
    </IonContent>
  </IonPage>
</template>

The swipe left/right events still works but it completely breaks browser based click events. The user can open the menu with the hamburger menu but can no longer close the menu when they click outside the menu overlay. Like i said above, this all works as it should WHEN i manually add the Header.vue code into each SPC, which is not ideal.

jQuery .each() for DOM objects not running; what am I missing?

I’m building an Html Partial for navigation in part of an MVC solution. All of the CSS, HTML, and JavaScript are contained in the partial. I would like to add the CSS class “current” to the current page within the navigation by running the navigation steps through a jQuery .each() function, but the function never executes (the debugger hits it and jumps over it). What could I be doing wrong? Thanks in advance!

HTML:

<div class="row navRow">
    <div class="col-md-3 text-center navStep" data-viewName="sftpaccount" onclick="window.location = '/Integration/SftpAccount';">
        <div class="stepFirst">Step 1</div>
    </div>
    <div class="col-md-3 text-center navStep" data-viewName="sftp_columnmapping" onclick="window.location = '/Integration/Sftp_ColumnMapping';">
        <div class="step">Step 2</div>
    </div>
    <div class="col-md-3 text-center navStep" data-viewName="sftp_documentmapping" onclick="window.location = '/Integration/Sftp_DocumentMapping';">
        <div class="step">Step 3</div>
    </div>
    <div class="col-md-3 text-center navStep" data-viewName="sftp_usermapping" onclick="window.location = '/Integration/Sftp_UserMapping';">
        <div class="stepLast">Step 4</div>
    </div>
</div>

JavaScript:

    var arrURL = window.location.pathname.split('/');
    var thisView = arrURL[arrURL.length - 1].toLowerCase();
    $('.navStep').each(function (i, element) {
        if (thisView == $(element).data('viewName')) {
            $(element).addClass('current');
        } else {
            $(element).removeClass('current');
        }
    })

How to expand interface

I expand my method getNews() and want to return any values (itemsValues – array, feedValues – object).

public getNews(): Promise<Array<RssInfo>> {
        const request = `https://api.news.com`;
        return this._ctx.httpClient
            .get(request, HttpClient.configurations.v1)
            .then((resp: HttpClientResponse) => {
                return resp.json();
            }).then((values: any) => {

                const itemsValues = values.items.map((v: any) => {
                    const post: RssInfo = {
                        title: v.title,
                        description: v.description,
                        content: v.content,
                        pubDate: v.pubDate,
                        author: v.author,
                        link: v.link,
                        enclosure: v.enclosure.link,
                    };
                    return post;
                });
                const feedValues = values.feed
                return [itemsValues, feedValues]
            })
    }

My RssInfo interface:

export default class RssInfo {
    title: string;
    description: string;
    content: string;
    pubDate?: string;
    author: string;
    link: string;
    enclosure?: string;
}

And I try to render in my component:
data[0] – this is my array, which I will map;
data1 – this is my object from which I will get values;

private loadData(): Promise<Array<RssInfo>> {
    return this.props.service.getNews().then((result: Array<RssInfo>) => {
      return result;
    });
  }

public componentDidMount(): void {
    this.loadData().then(data => {
      
      this.setState({
        items: data[0],
        feedInfo: data[1],
        isLoaded: true,
      });
    }).catch(error => { console.error(error); });
  }

But I have the next error
error
How can I fix it?

Canvas in React not loading font during the render of component

That’s my code:

import React, { useEffect, useRef } from "react";
import PropTypes from "prop-types";
import "../fonts/fonts.css";
import "../App.css";
import { motion } from "framer-motion";
import { useParams } from "react-router-dom";

const Canvas = ({ height, width, imageUrl, courseId }) => {
  const canvasRef = useRef(null);
  const { userId, userName } = useParams();

  function divideUserId(userId) {
    const cleanedUserId = userId.replace(/[^w]/g, "").toUpperCase();

    const parts = [];
    for (let i = 0; i < 3; i++) {
      const startIndex = i * 3;
      const endIndex = startIndex + 3;
      const part = cleanedUserId.slice(startIndex, endIndex);
      parts.push(part);
    }

    return parts;
  }

  const draw = (context) => {
    const date = new Date().toLocaleDateString();

    const kursyPomocniczne = [
      {
        secretId: "mat_podst",
        name: "Kurs do matury podstawowej",
      },
      {
        secretId: "mat_rozszerz",
        name: "Kurs do matury rozszerzonej",
      },
      {
        secretId: "mat_stud",
        name: "Kurs matematyki studenckiej",
      },
    ];

    const courseName = kursyPomocniczne.find(
      (course) => course.secretId === courseId
    ).name;

    const userText = userName.split("+").join(" ");
    const userTextWidth = context.measureText(userText).width;
    const userTextHeight = 40; // Zakładamy, że wysokość tekstu to 40px

    const canvasCenterX = context.canvas.width / 2;
    const canvasCenterY = context.canvas.height / 2;

    const userTextX = canvasCenterX - userTextWidth / 2;
    const userTextY = canvasCenterY + (userTextHeight + 117 / 2);

    const isFemale =
      userText && userText.charAt(userText.length - 1).toUpperCase() === "A";

    if (!isFemale) {
      context.strokeStyle = "#192e50";
      context.lineWidth = 4;
      context.beginPath();
      context.moveTo(501, 495);
      context.lineTo(490, 495);
      context.stroke();
      context.beginPath();
      context.moveTo(401, 536);
      context.lineTo(390, 536);
      context.stroke();
      context.beginPath();
      context.moveTo(721, 536);
      context.lineTo(710, 536);
      context.stroke();
    } else {
      context.strokeStyle = "#192e50";
      context.lineWidth = 4;
      context.beginPath();
      context.moveTo(705, 536);
      context.lineTo(694, 536);
      context.stroke();
    }

    context.fillStyle = "#192e50";
    context.font = "22px 'Serif', serif";
    context.fillText(date, 330, 608);
    context.fillStyle = "#192e50";
    context.font = "56px 'Great Vibes', cursive";
    context.fillText(userText, userTextX, userTextY);

    const courseCanvas = document.createElement("canvas");
    courseCanvas.width = 830;
    courseCanvas.height = 706;
    const courseContext = courseCanvas.getContext("2d");

    const courseCenterX = courseContext.canvas.width / 2;

    const courseTextWidth = courseContext.measureText(courseName).width;
    const courseTextX = courseCenterX - courseTextWidth / 2;

    courseContext.fillStyle = "#192e50";
    courseContext.font = "18px 'Serif', serif";
    courseContext.fillText(courseName.toUpperCase(), courseTextX, 520);

    context.drawImage(courseCanvas, 0, 0);

    const tempCanvas = context.canvas.cloneNode();
    const singContext = tempCanvas.getContext("2d");
    singContext.fillStyle = "#192e50";
    singContext.font = "9px 'Ubuntu', serif";
    singContext.justifyContent = "center";

    const parts = divideUserId(userId);

    parts.forEach((part, index) => {
      const partY = canvasCenterY - (40 - 572 / 2) + 10 * index;
      singContext.globalAlpha = 0.3;
      singContext.fillText(part, 881, partY);
    });

    context.drawImage(tempCanvas, 0, 0);

    singContext.clearRect(0, 0, tempCanvas.width, tempCanvas.height);
  };

  useEffect(() => {
    const canvas = canvasRef.current;
    const context = canvas.getContext("2d");
    const image = new Image();

    image.onload = () => {
      context.drawImage(image, 0, 0, width, height);
      draw(context);
    };
    image.src = imageUrl;
  }, [draw, height, width, imageUrl]);

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 2 }}
    >
      <canvas
        ref={canvasRef}
        height={height}
        width={width}
        className="rounded-xl mx-auto xl:w-4/5 xl:h-3/5 lg:w-3/5 lg:h-3/5  md:w-3/5 md:h-3/5 sm:w-3/5 sm:h-3/5 xs:w-3/5 xs:h-3/5"
      />
    </motion.div>
  );
};

Canvas.propTypes = {
  height: PropTypes.number.isRequired,
  width: PropTypes.number.isRequired,
  imageUrl: PropTypes.string.isRequired,
};

export default Canvas;

Well, I’ve tried almost every option with font face constructor, adding font face in App.css, creating file from where I’m importing this fonts, downloading fonts as a woff, as ttf and importing from folder, importing from google fonts link and none of them work.
The font is not being loaded as a component mounts, it actually has to load before the component is rendered so that for sure the font will be included. Now, I have to refresh the page to see this font. For default the font is being rendered as Comic Sans since it’s default cursive font. What should I do?

Chrome Extension: Prevent Page Reload When Clicking Timestamped Links on YouTube

I am currently developing a Chrome extension that generates timestamps for specific points in YouTube videos and displays them as clickable links on the page. The timestamped link format looks like this:

Assuming i manipulated a part of the youtube web page to display a list of time stamps

<li>
  <a href="https://www.youtube.com/watch?v=VdCcQ3m3yoo&t=0s">
    <strong>0:00</strong> - Introduction to the topic and the purpose of the video.
  </a>
</li>

My goal is to allow users to click on these timestamped links and have the video timeline navigate to the corresponding point without triggering a page refresh. However, currently, whenever I click on these links, the page reloads instead of smoothly navigating to the intended time in the video.

I have attempted another version of the link using a slightly different format:

<a href="watch?v=VdCcQ3m3yoo&t=0s">

But unfortunately, this approach also results in the page reloading upon clicking the link.

I’m seeking advice and guidance on how to resolve this issue. Is there a solution or workaround that I can implement in my Chrome extension to prevent the page from reloading while still enabling the smooth navigation to the specified time in the YouTube video? Any help would be greatly appreciated. Thank you!

Passing a prop from child to parent component

I am trying to change the press prop from within the child component to a parent component, but I get an ‘undefined is not a function’ error.

Here’s my child component:

const AddPlayerFieldComp = ({ teamId, pressed }) => {

    const handleAddUser = async () => {
        try {
            const addUserTeam = await API.graphql({
                query: mutations.createUserTeam,
                variables: variables
            });
            const response = addUserTeam.data;
            console.log("Added the user", JSON.stringify(response, null, 2));

           ** pressed(true);**

            }catch (e) {
                console.log("Error adding a player:", e);
            }
        };

    return (
        <View style={styles.addPlayerContainer}>
            <View style={styles.enterUserIdTextContainer}>
                <Text>ENTER USER ID:</Text>
            </View>
            <View style={styles.enterUserIdInputContainer}>
                <TextInput 
                    placeholder='user id...' 
                    value={newUser}
                    onChangeText={handleUserIdChange}
                />
            </View>
            <View style={styles.addPlayerIconContainer}>
**
                <TouchableOpacity onPress={handleAddUser}>**

                    <Ionicons name="person-add" size={30} color="#000" />
                </TouchableOpacity>
            </View>
        </View>

    )
};

And here’s my parent component:

import AddPlayerFieldComp from '../components/AddPlayerFieldComp';

const Teams = () => {

  const [press, setPress] = useState(false);

  const addPlayer = () => {
    setShowAddPlayerField(prevShowAddPlayerField => !prevShowAddPlayerField);
  };

  const handlePressChange = (value) => {
    console.log('handlePressChange called with value:', value);
    setPress(value)
  };

  return (
    
        {showPlayerList && (
          <Animated.View style={{ opacity: fadeAnim, transform: [{ scale: fadeAnim }], }}>
            <View>
              <View style={styles.popUpContainer}>
                <TeamUserList teamId={teamId} userId={userId} />
                <View style={styles.addPlayerContainer}>
                  <View style={styles.addPlayerIconContainer}>
                    <TouchableOpacity onPress={addPlayer}>
                      <SimpleLineIcons name="plus" size={40} color="#69B26C" />
                    </TouchableOpacity>
                  </View>
                  <View style={styles.addPlayerContainer}>
                    <Text style={styles.addPlayerText}>ADD A PLAYER</Text>
                  </View>
                </View>
                <View>
                  {showAddPlayerField === true && (
                    <AddPlayerFieldComp teamId={teamId} pressed={handlePressChange}/>
                  )}
                </View>
              </View>
            </View>

I’ve tried to pass the press prop to the child component and handle it in a function called ‘handlePressChange’ that would set the state of ‘press’ to the value of prop, however i get an ‘unhandled promise rejection’ and ‘typeerror: undefined is not a function’.

How to add schemas in Next.js 13 app router

tl;dr

Next.js 13’s /app router’s layout and page routing changes how we add content to the <head>. How can I add a schema script to each page? Next.js will automatically compile <head> tags placed in any layout or page into a single <head>. Use <script id="schema" type="application/ld+json" dangerouslySetInnerHTML={{__html: `{ "@context": "https://schema.org" }`}} /> to set the schema.

The goal

Just like in any website with great SEO, I want to include a schema script in the head of each page.

The history

Normally, this would be as easy as writing it in the <head> like so:

<!-- index.html -->
<head>
  <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      // ... the rest
    }
  </script>
</head>

Then, with the Next.js /pages directory it was a little different. It always felt weird to me to have to use the dangerouslySetInnerHTML attribute, but at least it worked.

// index.tsx
import Head from 'next/head'
export default function Page() {
  return (
    <Head>
      <script id="schema" type="application/ld+json" dangerouslySetInnerHTML={{__html: `
        {
          "@context": "https://schema.org",
          // ... the rest
        }
      `}} />
    </Head>
  )
}

The issue

Now with the introduction of the /app router, we’ve got great, new, simplified ways to set metadata, without having to directly import the <head> through next/head. In fact, the next/head component shouldn’t be used in the /app router.

So the question becomes…

How do we access the <head> on a page-per-page basis?

I was hoping the Next.js team would have already thought about this, and added schema to the new metadata variable, or even it’s own variable, but they don’t seem to have plans to do this as far as I can tell.

At first I thought the <head> could only be set in the RootLayout component. I thought, maybe if I used the RootLayout for the <html> tag alone, I could use the sub-layout files to define the <head> and <body>. This seemed like it would be such a pain though, since I would have to define a layout for every page, but at least it would work, right?

Scraping a site with JS

i am trying to scrape a web page, here is the JS code:

const axios = require('axios');
const cheerio = require('cheerio');

const r = 704290;
const link = 'https://www.discogs.com/sell/release/';
const link_completo = link + r.toString();
const headers = {
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0',
  'Referer': 'http://www.discogs.com'
};

console.log(link_completo);

axios.get(link_completo, { headers })
  .then((response) => {
    const $ = cheerio.load(response.data);

    const artist = $('h1').text();

    console.log('Artist:', artist.trim());
  });

here is the HTML:

<h1 class="title_1q3xW">
  <span class="link_15cpV">
    <a href="/artist/20991-The-Rolling-Stones" hreflang="en" class="link_1ctor link_15cpV">The Rolling Stones</a>
  </span> – <!-- -->Black And Blue
</h1>

here is the output:

Artist: The Rolling Stones
                     ‎–
                                                     Black And Blue

when i change the line

const artist = $('h1').text();

to get accurately the Artist name (The Rolling Stones)

const artist = $('.title_1q3xW').text()

i get no response

same with:

const artist = $('.link_15cpV').text()

This is my first question in Stack Overflow, be patience please if the question can be silly. Thank you for patience

const artist = $('.link_15cpV').text();
console.log(artist);
<h1 class="title_1q3xW"><span class="link_15cpV">
<a href="/artist/20991-The-Rolling-Stones" hreflang="en" class="link_1ctor link_15cpV">The Rolling Stones</a></span> –
  <!-- -->Black And Blue</h1>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

rock, paper, scissors simulation with JS

I am simulating rock paper scissors. What I want to do is these randomly moving divs (the divs are inside the object), I want them to change visually according to rock paper scissors rules. For example. When the stone encounters scissor1, its image becomes scissor1. The current code also moves randomly but I couldn’t change.

I was planning on touching each other with the control function and then seeing if they changed their visuals, but that just seemed too long and illogical.

enter image description here

let box = document.querySelector(".box");
let startBtn = document.querySelector(".start");

const objects = [
  { id: "rock", x: 530, y: 150, w: 25, h: 25, dx: 3, dy: 3, ani: {}, speed: 1, move: false  },
  { id: "paper", x: 420, y: 60, w: 25, h: 25, dx: 3, dy: 3, ani: {}, speed: 1, move: false},
  { id: "rock1", x: 210, y: 150, w: 25, h: 25, dx: 3, dy: 3, ani: {}, speed: 1, move: false  },
  { id: "paper1", x: 210, y: 60, w: 25, h: 25, dx: 3, dy: 3, ani: {}, speed: 1, move: false},
  { id: "scissors1", x: 10, y: 150, w: 25, h: 25, dx: 3, dy: 3, ani: {}, speed: 1, move: false  },
  { id: "scissors2", x: 410, y: 160, w: 25, h: 25, dx: 3, dy: 3, ani: {}, speed: 1, move: false},
];

  objects.forEach((data) => {
    console.log(data);
    let div = document.createElement("img");
    div.id = data.id;
    div.src = `/assets/${data.id}.png`;
    div.style.left = `${data.x}px`;
    div.style.top = `${data.y}px`;
    div.style.width = `${data.w}px`;
    div.style.height = `${data.h}px`;
    div.style.position = "absolute";
    box.appendChild(div);
  });
    

function check() {
 
}

startBtn.addEventListener("click", () => {
  if (!objects[0].move) {
    objects.forEach((obj) => {
      obj.ani = requestAnimationFrame(moveObject.bind(null, obj));
      obj.move = true;
    });
  } else {
    objects.forEach((obj) => {
      cancelAnimationFrame(obj.ani);
      obj.move = false;
    });
  }
});

function moveObject(obj) {
  if (obj.x > 600 - obj.w || obj.x < 0) {
    obj.dx *= -1;
  }
  if (obj.y > 400 - obj.h || obj.y < 0) {
    obj.dy *= -1;
  }

  obj.x += obj.dx * obj.speed;
  obj.y += obj.dy * obj.speed;

  document.getElementById(obj.id).style.left = `${obj.x}px`;
  document.getElementById(obj.id).style.top = `${obj.y}px`;

  if (obj.move) {
    obj.ani = requestAnimationFrame(moveObject.bind(null, obj));
  }
  check();
}

Calling eval with dynamically defined variables in scope

I want to be able to dynamically define variables (i.e x = 1, y = 2 – but where the user defines the names x and y, and may have a “z”) – and have them be in scope when executing javascript from a string (i.e. with eval()).

Obviously, this can be done statically like so:

var x = 1, y = 2;

eval('x + y');

But I want something like this:

var context = {};

userDefinedVariables.forEach(({name, value}) => context[name] = value);

eval('x + y'); //somehow call with context

Many answers suggest concatenating strings – like eval('var ' + names[0] + ' = ' + values[0]) but that’s prone to errors and code injection.

Many answers suggest modifying the global window and running eval in the global context.

How can I create a new local context for my eval execution that has access to my variable names? Something like eval().call(context)

MongoDB, find obj by user

I have 2 models in Next.js app, Booking and User. Obj bellow is booking obj.
When User booked some dates, new obj in booking is created. When user open booking details page, should see details of booking. I have a problem to select a specific object that belongs to the user. I was trying this, and it shows me all objects:

 _id: ObjectId(64b8440c8ff8e8950641fd7e)  // id of boooking obj
user: ObjectId(64b4cd15d0ef7c21d80ecd4d)  // id of user

in front end

const { user } = useSelector((state) => state.userAuth)
const userID = user?.user?._id

than I am using this userID to find specific obj

const res = await axios.post('/api/bookingDetails/bookDetails', userID, config ) 
// config is headers: {"Content-Type": "application/json"}

and in backend this code

const id = req.body.userID

const user = await Booking.find( id )
res.status(200).json({ 
     message: 'success ',
     user
    })